/// <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 keep literal tildes after paste and send", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/command_output_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  const replay = await fs.readFile(path.join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson"), "utf8");
  await fs.writeFile(fixture, replay.replaceAll("first fixture turn complete", REPLY.replaceAll('"', '\\"')));
  try {
    const project = await t3.project("demo", { "reports/~~final~~.txt": "Final report\n", "reports/~draft~.txt": "Draft report\n" });
    const thread = await t3.thread({ project, title: "Literal citation filenames", model: "command-output", messages: ["Update the final and draft reports."] });
    await t3.open(thread);
    await screen.getByRole("link", "~~final~~.txt", { exact: true }).waitFor();
    await screen.getByRole("button", "Copy message", { exact: true }).tap();
    const composer = screen.getByRole("textbox");
    await composer.tap();
    await browser.keyboard.press("ControlOrMeta+V");
    await app.screenshot("pasted-citations");
    await browser.keyboard.press("Enter");
    await screen.getByText("second fixture turn complete", { exact: true }).waitFor();
    await app.screenshot("sent-citations");
    const sent = await browser.evaluate(() => {
      const bodies = [...document.querySelectorAll("[data-user-message-body]")];
      const body = bodies.at(-1);
      return { text: body?.textContent, struck: body?.querySelectorAll("del").length, links: [...(body?.querySelectorAll("a") ?? [])].map(a => ({ text: a.textContent, href: a.getAttribute("href") })) };
    });
    expect(sent.struck).toBe(0);
    expect(sent.text).toContain("~~final~~.txt");
    expect(sent.text).toContain("~draft~.txt");
    expect(sent.links.some(link => link.href?.includes("reports/~~final~~.txt"))).toBe(true);
  } finally { await fs.writeFile(fixture, original); }
});
