import { readFile, writeFile } from "node:fs/promises";
import { setTimeout } from "node:timers/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("An unfinished list-contained fence stays buffered across internal blank lines", WEB, async ({ t3, app, screen, browser }) => {
  const transcriptPath = join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await readFile(transcriptPath, "utf8");
  const code = Array.from({ length: 35 }, (_, i) => `  // Add two numbers, example ${i + 1}.\n  function add${i + 1}(a: number, b: number): number {\n    return a + b;\n  }\n\n`).join("");
  const reply = "Intro: here are the TypeScript examples.\n\n- ```ts\n" + code + "  ```\nThat example includes 35 functions.";
  const frames = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: reply } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  await writeFile(transcriptPath, frames.map(frame => JSON.stringify(frame)).join("\n") + "\n");
  try {
    const project = await t3.project("Fence buffering");
    const thread = await t3.thread({ project, title: "List fence streaming", messages: ["Prepare"], model: "multi-turn" });
    await t3.open(thread);
    await screen.getByRole("textbox").waitFor();
    await browser.evaluate(() => window.t3dev.replay("showcase"));
    await screen.getByText("Intro: here are the TypeScript examples.", { exact: true }).waitFor();
    // Observe while replay emits every 30ms, well below the 800ms idle flush.
    await setTimeout(1800);
    await app.screenshot("open-fence-early");
    await setTimeout(1200);
    await app.screenshot("open-fence-later");
    let failure: unknown;
    try {
      await expect(browser.locator("li pre")).toBeHidden({ timeout: 100 });
    } catch (error) { failure = error; }
    await screen.getByText("That example includes 35 functions.", { exact: false }).waitFor({ timeout: 60000 });
    await screen.getByText("add35", { exact: true }).waitFor({ timeout: 60000 });
    await setTimeout(500);
    await app.screenshot("closed-fence-complete");
    if (failure) throw failure;
  } finally { await writeFile(transcriptPath, original); }
});
