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

// Synthetic ACP recording, installed identically in each app checkout before starting a turn.
const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const frame = (text: string, afterMs = 400) => ({type: "emit_inbound", afterMs, frame: {kind: "notification", method: "session/update", params: {sessionId: "replay", update: {sessionUpdate: "agent_message_chunk", content: {type: "text", text}}}}});
const paragraphs = (prefix: string, count: number) => Array.from({length: count}, (_, i) => frame(`${prefix} Paragraph ${i + 1}. Continuous prose keeps arriving during generation.\n\n`));
const turn = (frames: unknown[]) => [
  {type: "expect_outbound", frame: {kind: "request", method: "session/prompt"}},
  ...frames,
  {type: "emit_inbound", frame: {kind: "response", method: "session/prompt", result: {stopReason: "end_turn"}}},
];

test("Inline triple backticks preserve paragraph delivery and subsequent genuine fences", WEB, async ({t3, app, screen, browser}) => {
  const recording = [
    ...turn([frame("`npm test` runs the suite.\n\n", 200), ...paragraphs("Control", 30)]),
    ...turn([frame("```npm test``` runs the suite.\n\n", 200), ...paragraphs("Inline", 30)]),
    ...turn([
      frame("```a``` is inline.\n\n", 200),
      frame("Prose before the genuine code block.\n\n"),
      frame("```\n"),
      ...Array.from({length: 15}, (_, i) => frame(`code_line_${String(i + 1).padStart(2, "0")}\n${(i + 1) % 3 === 0 ? "\n" : ""}`, 350)),
      frame("```\n\n"),
      ...paragraphs("Following", 15),
    ]),
  ];
  await writeFile(join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson"), recording.map(row => JSON.stringify(row)).join("\n") + "\n");
  const project = await t3.project("Streaming demonstration");
  // A completed first turn selects the replay model; the subsequent UI turns use the same session.
  // The first turn is instead sent from the UI so all three streams are recorded.
  await t3.open();
  const stop = screen.getByRole("button", "Stop generation");
  const observations: Record<string, boolean> = {};
  const body = () => browser.evaluate(() => document.body.innerText);
  const send = async (prompt: string) => {
    await screen.getByRole("textbox").fill(prompt);
    await screen.getByRole("textbox").press("Enter");
    await stop.waitFor({state: "visible"});
  };
  await send("Control: stream single-backtick inline code, then 30 paragraphs.");
  await pause(4000);
  observations.controlStreams = (await body()).includes("Control Paragraph 3.");
  await app.screenshot("control-during-generation");
  await stop.waitFor({state: "hidden", timeout: 60000});

  await send("Scenario A: stream triple-backtick inline code, then 30 paragraphs.");
  await pause(4000);
  observations.inlineStreams = (await body()).includes("Inline Paragraph 3.");
  await app.screenshot("inline-during-generation");
  await stop.waitFor({state: "hidden", timeout: 60000});
  await app.screenshot("inline-completed");

  await send("Scenario B: inline triple backticks, prose, genuine fenced block with 15 lines and internal blank lines, then 15 paragraphs.");
  await pause(4000);
  observations.codeBuffered = !(await body()).includes("code_line_04");
  await app.screenshot("genuine-code-during-generation");
  await pause(6000);
  observations.followingStreams = (await body()).includes("Following Paragraph 3.");
  await app.screenshot("following-paragraphs-during-generation");
  await stop.waitFor({state: "hidden", timeout: 60000});
  await app.screenshot("genuine-code-completed");
  expect(observations).toEqual({controlStreams: true, inlineStreams: true, codeBuffered: true, followingStreams: true});
});
