import JSZip from "jszip";
import type { CapturedLog } from "../proxy/schemas";

async function fetchStreamingChunks(logId: number): Promise<string | null> {
  try {
    const response = await fetch(`/api/logs/${logId}/chunks`);
    if (!response.ok) return null;
    const data: unknown = await response.json();
    return JSON.stringify(data, null, 2);
  } catch {
    return null;
  }
}

export async function exportLogsAsZip(logs: CapturedLog[]): Promise<void> {
  const zip = new JSZip();

  // Add regular request/response files
  for (const log of logs) {
    if (log.rawRequestBody !== null) {
      zip.file(`#${log.id}.Request.json`, log.rawRequestBody);
    }
    if (log.responseText !== null) {
      zip.file(`#${log.id}.Response.json`, log.responseText);
    }
  }

  // Fetch SSE chunks in parallel for streaming logs
  const streamingLogs = logs.filter((log) => log.streaming);
  await Promise.allSettled(
    streamingLogs.map(async (log) => {
      const chunks = await fetchStreamingChunks(log.id);
      if (chunks !== null) {
        zip.file(`#${log.id}.SSE.Response.json`, chunks);
      }
    }),
  );

  // Generate and download ZIP
  const blob = await zip.generateAsync({ type: "blob" });
  const url = URL.createObjectURL(blob);

  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = `llm-inspector-export-${new Date().toISOString().slice(0, 10)}.zip`;
  document.body.appendChild(anchor);
  anchor.click();
  document.body.removeChild(anchor);

  URL.revokeObjectURL(url);
}
