/// <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("Copied Codex citation keeps literal dollar signs with math enabled", WEB, async ({ t3, app, browser, screen }) => {
  // The replay provider supplies synthetic text for this client-only rendering reproduction.
  const fixture = `${APP_DIR}/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const citation = 'See :codex-file-citation{path="/tmp/$x$.txt"} for details.';
  const frames = original.trim().split("\n").map(line => JSON.parse(line));
  for (const entry of frames) {
    if (entry.label === "first.assistant") entry.frame.params.update.content.text = citation;
  }
  const project = await t3.project("citation-demo");
  await writeFile(fixture, frames.map(entry => JSON.stringify(entry)).join("\n") + "\n");
    await t3.open("/settings/appearance");
    await screen.getByRole("switch", "Render math", { exact: true }).tap();
    const thread = await t3.thread({ project, title: "Dollar filename citation", messages: ["Show the file citation"] });
    await t3.open(thread);
    await screen.getByRole("link", "$x$.txt", { exact: true }).waitFor();
    await screen.getByRole("button", "Copy message", { exact: true }).last().tap();
    await screen.getByRole("textbox").tap();
    await browser.keyboard.press("ControlOrMeta+V");
    await app.screenshot("copied-citation-in-composer");
    await browser.keyboard.press("Enter");
    await screen.getByText("second fixture turn complete").waitFor();
    await app.screenshot("reposted-citation");
    const result = await browser.evaluate(() => {
      const body = [...document.querySelectorAll("[data-user-message-body]")].at(-1);
      const link = body?.querySelector('a');
      return { math: body?.querySelectorAll('[data-markdown-math]').length, text: body?.textContent, target: link?.getAttribute("href") };
    });
    expect(result.math, "Reposted filename must not become inline math").toBe(0);
    expect(result.text).toContain("$x$.txt");
    expect(result.target).toContain("/tmp/$x$.txt");
  // scenarios:prove removes this disposable app checkout after fixture cleanup.

});
