import { runClaudeCodeAgent, runCodexAgent, runOllamaAgent } from '@/lib/agent-engines.js';
import { requireSession } from '@/lib/auth.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

const PING_PROMPT = 'Reply with exactly: pong';

export async function POST(req) {
  let body;
  try { body = await req.json(); } catch { return new Response('Invalid JSON', { status: 400 }); }
  try {
    await requireSession(req);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    throw err;
  }
  const engine = String(body.engine || '');
  const model = String(body.model || '');
  const start = Date.now();
  try {
    let output;
    if (engine === 'claude-code') {
      output = await runClaudeCodeAgent({ systemPrompt: '', userMessage: PING_PROMPT });
    } else if (engine === 'codex') {
      output = await runCodexAgent({ systemPrompt: '', userMessage: PING_PROMPT });
    } else if (engine === 'ollama') {
      output = await runOllamaAgent({ model, systemPrompt: '', userMessage: PING_PROMPT, maxTokens: 16 });
    } else {
      return new Response(`Unknown engine: ${engine}`, { status: 400 });
    }
    return Response.json({ ok: true, engine, model, output: output.slice(0, 200), ms: Date.now() - start });
  } catch (err) {
    return Response.json({ ok: false, engine, model, error: err.message, ms: Date.now() - start }, { status: 200 });
  }
}
