/// <reference lib="dom" />
import { readFile } from "node:fs/promises";
import { setTimeout } from "node:timers/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Sent file mentions preserve literal angle brackets", WEB, async ({ t3, app, screen, browser }) => {
  const capture = async (label: string) => {
    // Hold each interaction for the recording and verify the still has settled.
    await setTimeout(1500);
    let previous = await app.screenshot(`${label}-stability`);
    for (let attempt = 0; attempt < 6; attempt++) {
      await setTimeout(500);
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error(`Capture ${label} did not settle`);
  };
  const project = await t3.project("angle-mentions", {
    "src/a<x@y.com>b.ts": "export const email = true;\n",
    "src/a<T>.ts": "export const generic = true;\n",
  });
  const thread = await t3.thread({ project, title: "Literal file names", messages: ["Hello"], model: "multi-turn" });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.pressSequentially("look at @a<x");
  await screen.getByRole("option", "a<x@y.com>b.ts", { exact: false }).waitFor();
  await capture("email-file-picker");
  await screen.getByRole("option", "a<x@y.com>b.ts", { exact: false }).tap();
  await composer.pressSequentially(" and @a<T");
  await screen.getByRole("option", "a<T>.ts", { exact: false }).waitFor();
  await capture("tag-file-picker");
  await screen.getByRole("option", "a<T>.ts", { exact: false }).tap();
  await capture("composed-file-mentions");
  await browser.keyboard.press("Enter");
  await screen.getByRole("link", "a<x@y.com>b.ts", { exact: true }).waitFor();
  await screen.getByText("second fixture turn complete", { exact: true }).waitFor();
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  await capture("sent-file-mentions");
  const rendered = await browser.evaluate(() => {
    const body = [...document.querySelectorAll("[data-user-message-body]")].find(el => el.textContent?.includes("look at"));
    return { text: body?.textContent?.replace(/\s+/g, " ").trim(), mailto: body?.querySelectorAll('a[href^="mailto:"]').length };
  });
  expect(rendered).toEqual({ text: "look at a<x@y.com>b.ts and a<T>.ts", mailto: 0 });
});
