import type { TSurveyGenerationStreamEvent } from "@/app/api/internal/surveys/generate/lib/events";
import type { TV3SurveyGenerateBody } from "@/app/api/v3/surveys/generate/schemas";
import { parseV3ApiError } from "@/modules/api/lib/v3-client";
import { NdjsonParser } from "./ai-stream-parser";

const STREAM_ENDPOINT = "/api/internal/surveys/generate/stream";

/**
 * Read the survey-generation stream, handing each event to `onEvent` as it arrives.
 *
 * A pre-stream failure still comes back as `problem+json`, so a non-OK response throws a
 * `V3ApiError` exactly like the blocking endpoint — the caller's existing error handling covers it
 * unchanged. Failures *after* the body opened arrive as `error` events instead, because the status
 * code is already spent by then.
 */
export async function streamSurveyGeneration(
  body: TV3SurveyGenerateBody,
  {
    signal,
    onEvent,
  }: {
    signal: AbortSignal;
    onEvent: (event: TSurveyGenerationStreamEvent) => void;
  }
): Promise<void> {
  const response = await fetch(STREAM_ENDPOINT, {
    method: "POST",
    cache: "no-store",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
    signal,
  });

  if (!response.ok) {
    throw await parseV3ApiError(response);
  }

  await readSurveyDraftStream(response, onEvent);
}

/**
 * Hand each NDJSON event of an opened draft stream to `onEvent`, until the body ends. Shared by the
 * generation stream and the import stream, which differ only in how they open the request.
 */
export async function readSurveyDraftStream<TEvent extends { type: string }>(
  response: Response,
  onEvent: (event: TEvent) => void
): Promise<void> {
  if (!response.body) {
    throw new Error("The survey stream returned no body.");
  }

  const reader = response.body.getReader();
  // TextDecoder with { stream: true } rather than TextDecoderStream, so the line splitting stays a
  // pure string function that can be unit-tested without constructing a stream.
  const decoder = new TextDecoder();
  const parser = new NdjsonParser<TEvent>();
  let sawTerminalEvent = false;

  const handle = (event: TEvent) => {
    if (event.type === "done" || event.type === "error") {
      sawTerminalEvent = true;
    }
    onEvent(event);
  };

  try {
    for (;;) {
      const { done, value } = await reader.read();
      if (done) break;

      parser.push(decoder.decode(value, { stream: true })).forEach(handle);
    }

    parser.flush().forEach(handle);
  } finally {
    reader.releaseLock();
  }

  // A body that ends after only partials — a dropped connection, a proxy cutting the response, or a
  // terminal frame mangled past parsing — would otherwise leave the caller waiting on an event that
  // is never coming, stuck in its generating state with the unload guard still armed.
  if (!sawTerminalEvent) {
    throw new Error("The survey stream ended without a result.");
  }
}
