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

// Synthetic ACP recording, shared unchanged by the two app revisions.
const paragraph = (prefix: string, n: number) => `${prefix} Paragraph ${n}. ${"Continuous prose keeps arriving while this completed paragraph should already be visible to the reader. ".repeat(3)}\n\n`;
const turns: string[][] = [
  ["Ready for streaming reproduction."],
  ["`npm test` runs the suite.\n\n", ...Array.from({length: 30}, (_, i) => paragraph("Control", i+1))],
  ["```npm test``` runs the suite.\n\n", ...Array.from({length: 30}, (_, i) => paragraph("Scenario A", i+1))],
  ["```a``` is inline.\n\n", "Scenario B introductory prose.\n\n", "```\n", ...Array.from({length:15}, (_,i) => `code_line_${i+1}\n${(i+1)%3===0 ? "\n" : ""}`), "```\n\n", ...Array.from({length:15}, (_,i) => paragraph("Scenario B", i+1))],
];
const entries = turns.flatMap(texts => [
  {type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}},
  ...texts.map(text => ({type:"emit_inbound",afterMs:100,frame:{kind:"notification",method:"session/update",params:{sessionId:"synthetic",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text}}}}})),
  {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}},
]);

test("Inline triple backticks preserve continuous paragraph delivery and real code fences", WEB, async ({t3, app, screen, browser}) => {
  writeFileSync(`${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`, entries.map(x=>JSON.stringify(x)).join("\n"));
  const project = await t3.project("streaming-proof");
  const thread = await t3.thread({project,title:"Inline fence streaming",messages:["Prepare reproduction"],model:"showcase"});
  await t3.open(thread);
  const observations: Record<string, boolean> = {};
  const pause = (ms: number) => new Promise(resolve=>setTimeout(resolve,ms));
  const send = async (text: string) => {
    await screen.getByRole("textbox").fill(text);
    await screen.getByRole("textbox").press("Enter");
  };
  for (const [label,prompt,prefix] of [
    ["control", "Stream the single-backtick control", "Control"],
    ["inline-code", "Stream Scenario A with inline triple backticks", "Scenario A"],
  ]) {
    await send(prompt);
    await pause(4000);
    observations[label] = await browser.evaluate((p:string) => document.body.innerText.includes(`${p} Paragraph 3.`) && !!document.querySelector('[aria-label="Stop generation"]'),prefix);
    await app.screenshot(`${label}-during-generation`);
    await screen.getByRole("button","Stop generation").waitFor({state:"hidden",timeout:60000});
    await app.screenshot(`${label}-completed`);
  }
  await send("Stream Scenario B with inline code then a genuine fenced block");
  await pause(1500);
  await app.screenshot("real-code-block-during-generation");
  observations["code-boundary"] = await browser.evaluate(() => !document.body.innerText.includes("code_line_6"));
  await pause(4000);
  observations["following-prose"] = await browser.evaluate(() => document.body.innerText.includes("Scenario B Paragraph 3.") && !!document.querySelector('[aria-label="Stop generation"]'));
  await app.screenshot("following-prose-during-generation");
  await screen.getByRole("button","Stop generation").waitFor({state:"hidden",timeout:60000});
  await app.screenshot("real-code-block-completed");
  await expect(observations).toEqual({control:true,"inline-code":true,"code-boundary":true,"following-prose":true});
});
