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

const MESSAGE = '| File | Note |\n| --- | --- |\n| :codex-file-citation{path="reports/a&#124;b.txt"} | ok |';

test("Copying a citation with a pipe preserves its table row in Markdown preview", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("citation-demo", { "reports/a|b.txt": "Citation target\n", "copied.md": "" });
  const recording = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
  const original = await fs.readFile(recording, "utf8");
  let thread;
  try {
    await fs.writeFile(recording, [
      { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
      { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: MESSAGE } } } } },
      { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
    ].map(entry => JSON.stringify(entry)).join("\n"));
    thread = await t3.thread({ project, title: "Copy citation table", messages: ["Reply with the citation table"], model: "command-output" });
  } finally {
    await fs.writeFile(recording, original);
  }
  await t3.open(thread);
  await screen.getByRole("link", "a|b.txt", { exact: true }).waitFor({ state: "visible" });
  await app.screenshot("original-table");
  await browser.evaluate(() => {
    const originalWrite = navigator.clipboard.writeText.bind(navigator.clipboard);
    navigator.clipboard.writeText = async (text) => {
      document.documentElement.dataset.copiedMarkdown = text;
      return originalWrite(text);
    };
    return null;
  });
  await screen.getByRole("button", "Copy message", { exact: true }).last().tap();
  const copied = await browser.evaluate(() => document.documentElement.dataset.copiedMarkdown ?? "");
  if (!copied) throw new Error("Copy message did not write Markdown");
  await fs.writeFile(`${project}/copied.md`, copied);
  // Open the copied file through a second seeded message's file citation.
  const preview = await t3.thread({ project, title: "Copied Markdown", messages: ['Open :codex-file-citation{path="copied.md"}'] });
  await t3.open(preview);
  await screen.getByRole("button", /^Agent Open/).tap();
  await screen.getByRole("link", /^copied.md/).tap();
  await screen.getByRole("button", "Show rendered markdown").tap();
  await app.screenshot("copied-table-preview");
  const cells = await browser.evaluate(() => {
    const tables = [...document.querySelectorAll("table")];
    return tables.map(table => [...table.querySelectorAll("tbody tr")].map(row => [...row.querySelectorAll("td")].map(cell => ({ text: cell.textContent, link: cell.querySelector("a")?.textContent ?? null }))));
  });
  expect(cells).toEqual([[[{ text: "a|b.txt", link: "a|b.txt" }, { text: "ok", link: null }]]]);
  await screen.getByRole("link", "a|b.txt", { exact: true }).tap();
  await app.screenshot("copied-link-opened");
});
