import { NextResponse } from 'next/server';
import { readFile } from 'fs/promises';
import { homedir } from 'os';
import { join } from 'path';
import { existsSync } from 'fs';

const IS_MAC = process.platform === 'darwin';

export async function GET() {
  const logPaths = [
    join(homedir(), '.ollama', 'logs', 'server.log'),
    join(homedir(), '.ollama', 'logs', 'gpu.log'),
    '/tmp/ollama.log',
    // Linux / WSL2 — journalctl may write here
    '/var/log/ollama.log',
  ];

  for (const logPath of logPaths) {
    if (existsSync(logPath)) {
      try {
        const content = await readFile(logPath, 'utf-8');
        // Return last 100 lines
        const lines = content.split('\n').filter(Boolean);
        const tail = lines.slice(-100);
        return NextResponse.json({ lines: tail, path: logPath, total: lines.length });
      } catch (err) {
        return NextResponse.json({ error: String(err), lines: [] }, { status: 500 });
      }
    }
  }

  // Fallback: platform-specific logging hint
  const hint = IS_MAC
    ? 'Ollama uses macOS unified logging. Use: log show --predicate \'subsystem == "com.ollama"\' --last 5m'
    : 'Ollama logs not found. If running on Windows (accessed via WSL2), check Windows Event Viewer or: journalctl -u ollama --no-pager -n 50';

  return NextResponse.json({
    lines: [hint],
    path: 'system',
    total: 1,
  });
}
