import { createFileRoute } from "@tanstack/react-router";
import { onLogUpdate, getFilteredLogs, getLogSessionId } 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;
        let cleanedUp = false;

        const unsubscribe = onLogUpdate((log: CapturedLog) => {
          if (controllerRef === null) return;
          // Filter by session/model if specified
          if (sessionId !== undefined && getLogSessionId(log) !== 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 {
            cleanup();
          }
        });

        const cleanup = (): void => {
          if (cleanedUp) return;
          cleanedUp = true;
          clearInterval(heartbeat);
          unsubscribe();
          controllerRef = null;
          request.signal.removeEventListener("abort", cleanup);
        };

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

        request.signal.addEventListener("abort", cleanup, { once: true });

        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() {
            cleanup();
          },
        });

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