/// <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 RAW = "Before :codex-followup[[Guide](https://example.com/a]b)]{prompt=go} after\n\nBefore :codex-followup[**[Guide](https://example.com/a]b)**]{prompt=go} after";
const EXPECTED = "Before [Guide](https://example.com/a]b) after\n\nBefore **[Guide](https://example.com/a]b)** after";

test("Copying Codex follow-ups preserves closing URL brackets and bold formatting", 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");
  try {
    await FS.writeFile(fixture, [
      { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: {} } },
      { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: RAW } } } } },
      { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
    ].map((entry) => JSON.stringify(entry)).join("\n"));
    const project = await t3.project("link-copy-demo");
    const thread = await t3.thread({ project, title: "Copy follow-up links", model: "command-output", messages: ["Show the plain and bold follow-up links."] });
    await t3.open(thread);
    await screen.getByRole("link", "Guide", { exact: true }).first().waitFor();
    await app.screenshot("rendered-links");
    await browser.evaluate(() => {
      const write = navigator.clipboard.writeText.bind(navigator.clipboard);
      navigator.clipboard.writeText = async (text) => {
        document.documentElement.dataset.copiedMarkdown = text;
        await write(text);
      };
    });
    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("copied-links-pasted");
    expect(await browser.evaluate(() => document.documentElement.dataset.copiedMarkdown)).toBe(EXPECTED);
  } finally {
    await FS.writeFile(fixture, original);
  }
});
