import { getHermesJob, listHermesJobEvents } from '@/lib/hermes-jobs.js';

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

function send(ctrl, event, data) {
  ctrl.enqueue(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
}

export async function GET(_, { params }) {
  const { id } = await params;
  if (!getHermesJob(id)) return Response.json({ error: 'not found' }, { status: 404 });

  const encoder = new TextEncoder();
  let lastCount = 0;
  const stream = new ReadableStream({
    async start(ctrl) {
      const write = {
        enqueue(chunk) { ctrl.enqueue(encoder.encode(chunk)); },
      };
      const interval = setInterval(() => {
        try {
          const events = listHermesJobEvents(id, 500);
          for (const event of events.slice(lastCount)) {
            send(write, event.type || 'event', event);
          }
          lastCount = events.length;
          const job = getHermesJob(id);
          if (['complete', 'failed', 'cancelled', 'stale'].includes(job?.status)) {
            send(write, 'done', { status: job.status });
            clearInterval(interval);
            ctrl.close();
          }
        } catch (error) {
          send(write, 'error', { message: error.message });
          clearInterval(interval);
          ctrl.close();
        }
      }, 1000);
    },
  });

  return new Response(stream, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache, no-transform',
      Connection: 'keep-alive',
      'X-Accel-Buffering': 'no',
    },
  });
}
