/// <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";

const REPLY = 'I updated :codex-file-citation{path="reports/~~final~~.txt"} and :codex-file-citation{path="reports/~draft~.txt"}.';

test("Copied Codex citations retain literal tilde filenames", 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, [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: REPLY } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map((entry) => JSON.stringify(entry)).join("\n"));
  try {
    const project = await t3.project("reports-demo", { "reports/~~final~~.txt": "Final report\n", "reports/~draft~.txt": "Draft report\n" });
    const thread = await t3.thread({ project, title: "Literal filenames", model: "showcase", messages: ["Update the two reports."] });
    await t3.open(thread);
    await screen.getByRole("link", "~~final~~.txt", { exact: true }).waitFor();
    await screen.getByRole("button", "Copy message", { exact: true }).last().tap();
    const composer = screen.getByRole("textbox");
    await composer.tap();
    await browser.keyboard.press("ControlOrMeta+V");
    await app.screenshot("pasted-citations");
    const pasted = await browser.evaluate(() => document.querySelector('[contenteditable="true"]')?.textContent ?? "");
    await composer.press("Enter");
    await screen.getByRole("button", "Submit message", { exact: true }).waitFor();
    await app.screenshot("sent-citations");
    expect(pasted.replaceAll("\\", "")).toContain("~~final~~.txt");
    expect(pasted.replaceAll("\\", "")).toContain("~draft~.txt");
    const links = await browser.evaluate(() => [...document.querySelectorAll('a')].filter((a) => a.textContent?.includes("final") || a.textContent?.includes("draft")).map((a) => ({ label: a.textContent, href: a.getAttribute("href") })));
    expect(links.filter((link) => link.label === "~~final~~.txt").length).toBe(3);
    expect(new Set(links.filter((link) => link.label === "~~final~~.txt").map((link) => link.href)).size).toBe(1);
    expect(await browser.evaluate(() => document.querySelectorAll("del").length)).toBe(0);
  } finally {
    await fs.writeFile(fixture, original);
  }
});
