import { createFileRoute } from "@tanstack/react-router";
import { onLogUpdate, getFilteredLogs } from "../../proxy/store";
import { type CapturedLog } from "../../proxy/schemas";

export const Route = createFileRoute("/api/logs/stream")({
  server: {
    handlers: {
      GET: ({ request }: { request: Request }) => {
        const url = new URL(request.url);
        const sessionId = url.searchParams.get("sessionId") ?? undefined;
        const model = url.searchParams.get("model") ?? undefined;

        let controllerRef: ReadableStreamDefaultController<Uint8Array> | null = null;

        // Send heartbeat comment every 30s to keep connection alive
        const heartbeat = setInterval(() => {
          if (controllerRef) {
            try {
              controllerRef.enqueue(new TextEncoder().encode(": heartbeat\n\n"));
            } catch {
              // Stream closed
            }
          }
        }, 30000);

        const unsubscribe = onLogUpdate((log: CapturedLog) => {
          if (!controllerRef) return;
          // Filter by session/model if specified
          if (sessionId !== undefined && log.sessionId !== sessionId) return;
          if (model !== undefined && log.model !== model) return;
          try {
            const data = `data: ${JSON.stringify({ type: "update", log })}\n\n`;
            controllerRef.enqueue(new TextEncoder().encode(data));
          } catch {
            // Stream closed
          }
        });

        const stream = new ReadableStream<Uint8Array>({
          start(controller) {
            controllerRef = controller;
            // Send initial batch of logs immediately
            const logs = getFilteredLogs(sessionId, model);
            const initData = `data: ${JSON.stringify({ type: "init", logs })}\n\n`;
            controller.enqueue(new TextEncoder().encode(initData));
          },
          cancel() {
            clearInterval(heartbeat);
            unsubscribe();
            controllerRef = null;
          },
        });

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