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

test("Copying a nested follow-up preserves its citation and suffix", WEB, async ({ t3, app, browser, screen }) => {
  const transcript = join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await readFile(transcript, "utf8");
  const text = ':codex-followup[read :codex-file-citation[a]{path="a.ts"} then]{prompt="o"} end';
  const frames = [
    { type: "transcript_start", provider: "acpRegistry", protocol: "acp.ndjson-jsonrpc", version: "1" },
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } },
  ];
  await writeFile(transcript, frames.map((frame) => JSON.stringify(frame)).join("\n") + "\n");
  try {
    const project = await t3.project("demo", { "a.ts": "export const a = 1;\n" });
    const thread = await t3.thread({ project, title: "Nested follow-up", model: "showcase", messages: ["go"] });
    await t3.open(thread);
    await screen.getByRole("button", "Copy message", { exact: true }).waitFor();
    await browser.evaluate(() => {
      const write = navigator.clipboard.writeText.bind(navigator.clipboard);
      navigator.clipboard.writeText = async (text) => {
        document.body.dataset.copiedText = text;
        await write(text);
      };
    });
    await screen.getByRole("button", "Copy message", { exact: true }).tap();
    await screen.getByRole("textbox").tap();
    await browser.keyboard.press("ControlOrMeta+V");
    await app.screenshot("copied-followup-pasted");
    const copied = await browser.evaluate(() => document.body.dataset.copiedText);
    expect(copied).toBe("read [a.ts](<a.ts>) then end");
  } finally {
    await writeFile(transcript, original);
  }
});
