import { getAgent } from '@/lib/runtime.js';
import { runAgentTick } from '@/lib/agent-runner.js';

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

// Fire-and-forget manual run. The dashboard SSE stream (`agent_run_start` /
// `agent_run_complete`) drives the UI, so this route returns immediately and
// lets the run finish in the background — otherwise the request would block
// for the full duration of the tick and the button would lock up.
export async function POST(_req, { params }) {
  const { id } = await params;
  const agent = getAgent(id);
  if (!agent) return Response.json({ ok: false, error: 'agent not found' }, { status: 404 });

  runAgentTick(id, { triggered_by: 'manual' }).catch(err => {
    console.warn(`[agents/${id}/run] tick failed:`, err?.message || err);
  });

  return Response.json({ ok: true, agent_id: id, status: 'queued' });
}
