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

const INVALID = [
  'Empty: :codex-followup[open :codex-file-citation[x]{path=/tmp/a.ts}]{prompt=""}',
  'Missing: :codex-followup[read :codex-file-citation[a]{path="/tmp/b.ts"}] end',
  'Blank: :codex-followup[read :codex-file-citation[a]{path="/tmp/c.ts"}]{prompt="   "} end',
].join("\n\n");
const MESSAGE = INVALID + '\n\nValid: :codex-followup[open :codex-file-citation[x]{path=/tmp/d.ts}]{prompt="Open it"}';
const EXPECTED = INVALID + '\n\nValid: open [d.ts](</tmp/d.ts>)';

test("Copy preserves invalid follow-ups and expands the valid follow-up", WEB, async ({ t3, app, browser, screen }) => {
  // Supply the reported text through the built-in replay model, keeping the real message pipeline.
  const fixture = join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await readFile(fixture, "utf8");
  const template = await readFile(join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson"), "utf8");
  await writeFile(fixture, template.split("\n").map(line => {
    if (!line) return line;
    const entry = JSON.parse(line);
    if (entry.label === "first.assistant") entry.frame.params.update.content.text = MESSAGE;
    return JSON.stringify(entry);
  }).join("\n"));
  try {
    const project = await t3.project("directive-copy");
    const thread = await t3.thread({ project, title: "Literal follow-up copy", model: "default", messages: ["Show the four follow-up examples."] });
    await t3.open(thread);
    await screen.getByText("Valid: open", { exact: false }).waitFor();
    await app.screenshot("rendered-followups");
    await screen.getByRole("button", "Copy message", { exact: true }).last().tap();
    const composer = screen.getByRole("textbox");
    await composer.tap();
    await browser.evaluate(() => {
      document.addEventListener("paste", event => {
        document.body.dataset.copiedText = event.clipboardData?.getData("text/plain") ?? "";
      }, { once: true });
      return null;
    });
    await browser.keyboard.press("ControlOrMeta+V");
    await app.screenshot("copied-followups-pasted");
    const copied = await browser.evaluate(() => document.body.dataset.copiedText ?? "");
    expect(copied).toBe(EXPECTED);
  } finally {
    await writeFile(fixture, original);
  }
});
