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

test("BOM insertion and removal stay visible while ignoring whitespace", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const threads = [];
  try {
    for (const [label, oldText, newText] of [
      ["Insert a byte-order mark", "x\n", "\uFEFFx\n"],
      ["Remove the byte-order mark", "\uFEFFx\n", "x\n"],
    ]) {
      const project = await t3.project(label, { main: oldText });
      const updates = [
        { sessionUpdate: "tool_call", toolCallId: "bom", kind: "edit", title: "Edit main", status: "completed", content: [{ type: "diff", path: "main", oldText, newText }] },
        { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "BOM edit recorded." } },
      ];
      await writeFile(fixture, [
        { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
        ...updates.map(update => ({ type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update } } })),
        { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
      ].map(x => JSON.stringify(x)).join("\n") + "\n");
      let thread;
      try { thread = await t3.thread({ project, title: label, messages: [label], model: "default" }); }
      catch (error) {
        if (!String(error).includes("Model default is not advertised")) throw error;
        thread = await t3.thread({ project, title: label, messages: [label], model: "showcase" });
      }
      threads.push({ label, thread });
    }
  } finally { await writeFile(fixture, original); }
  const results = [];
  for (const { label, thread } of threads) {
    await t3.open(thread);
    await screen.getByText("BOM edit recorded.", { exact: true }).waitFor();
    await screen.getByRole("button", "Worked for", { exact: false }).tap();
    await screen.getByRole("button", "Changed 1 file", { exact: false }).tap();
    await screen.getByRole("button", "Open diff", { exact: true }).tap();
    await screen.getByRole("button", "Show whitespace changes", { exact: true }).waitFor();
    await screen.getByRole("button", "Collapse main", { exact: true }).waitFor();
    await screen.getByRole("button", "Changed 1 file", { exact: false }).tap();
    await app.screenshot(label);
    results.push(await browser.evaluate(() => Array.from(document.querySelectorAll("*")).flatMap(host => Array.from(host.shadowRoot?.querySelectorAll('[data-line][data-line-type]') ?? [], line => line.getAttribute("data-line-type")))));
  }
  for (const lines of results) {
    expect(lines).toContain("change-addition");
    expect(lines).toContain("change-deletion");
  }
});
