/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

// Replay the exact Markdown from the reported reproduction, holding each turn open for capture.
const update = (text: string, afterMs = 250) => ({ type: "emit_inbound", afterMs, frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } });
const turn = (text: string, hold = false) => [
  { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
  update(text),
  ...(hold ? Array.from({ length: 4 }, () => update("", 2000)) : []),
  { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
];

test("Streaming NBSP preserves code fences and paragraphs", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  await fs.writeFile(fixture, [...turn("Ready."), ...turn("```text\nbody\n```\u00a0\n\nafter\n```", true), ...turn("alpha\n\u00a0\nbeta", true)].map(row => JSON.stringify(row)).join("\n"));
  try {
    const project = await t3.project("markdown-demo");
    const thread = await t3.thread({ project, title: "Markdown streaming", model: "showcase", messages: ["Ready"] });
    await t3.open(thread);
    const read = () => browser.evaluate(() => {
      const blocks = [...document.querySelectorAll(".chat-markdown")];
      const el = blocks.at(-1);
      return { streaming: el?.hasAttribute("data-streaming") ?? false, code: [...(el?.querySelectorAll("pre") ?? [])].map(p => p.textContent), paragraphs: [...(el?.querySelectorAll("p") ?? [])].map(p => p.textContent), text: el?.textContent ?? "" };
    });
    const send = async (message: string) => {
      await screen.getByRole("textbox").fill(message);
      await screen.getByRole("textbox").press("Enter");
    };
    await send("Show a Markdown code fence");
    await expect.poll(async () => { const state = await read(); return state.streaming && state.text.includes("after"); }).toBe(true);
    await screen.getByText("body", { exact: true }).waitFor();
    await app.screenshot("fence-streaming");
    const fence = await read();
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 60000 });
    await app.screenshot("fence-settled");
    const settledFence = await read();
    await send("Now a paragraph");
    await expect.poll(async () => { const state = await read(); return state.streaming && state.text.includes("beta"); }).toBe(true);
    await app.screenshot("paragraph-streaming");
    const paragraph = await read();
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 60000 });
    await app.screenshot("paragraph-settled");
    const settledParagraph = await read();
    expect({ fence: fence.code, paragraph: paragraph.paragraphs, settledFence: settledFence.code, settledParagraph: settledParagraph.paragraphs }).toEqual({ fence: settledFence.code, paragraph: settledParagraph.paragraphs, settledFence: ["body\n```\u00a0\n\nafter\n"], settledParagraph: ["alpha\n\u00a0\nbeta"] });
  } finally {
    await fs.writeFile(fixture, original);
  }
});
