import { readFile } from "node:fs/promises";
import { setTimeout } from "node:timers/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("ACP compares opaque message IDs exactly", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("ACP opaque IDs");
  await t3.thread({ project, title: "Distinct IDs must stay separate", messages: ['Chunks: "answer" → A; " answer " → B. Expect A and B.'], model: "showcase" });
  await t3.thread({ project, title: "Identical padded IDs must append", messages: ['ID " answer ": full A, then chunk B. Expect AB.'], model: "todo-list" });
  await t3.open();
  await screen.getByRole("button", "Toggle thread details panel").tap();
  const capture = async (label: string) => {
    const work = screen.getByRole("button", /^Worked for/);
    if (await work.isVisible()) await work.tap();
    // Manual evidence requires two identical captures 500ms apart before the final still.
    let previous = await app.screenshot(`${label}-stability`);
    for (let attempt = 0; attempt < 5; attempt++) {
      await setTimeout(500);
      const current = await app.screenshot(`${label}${attempt ? `-${attempt}` : ""}`);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error("The evidence viewport did not settle");
  };
  await screen.getByRole("button", /^Distinct IDs must stay separate,/).tap();
  await browser.locator('[data-message-role="assistant"]').first().waitFor();
  await capture("distinct-opaque-ids");
  await screen.getByRole("button", /^Identical padded IDs must append,/).tap();
  await browser.locator('[data-message-role="assistant"]').first().waitFor();
  await capture("same-padded-id");
  await expect(screen.getByText("AB", { exact: true })).toBeVisible();
  await screen.getByRole("button", /^Distinct IDs must stay separate,/).tap();
  await expect(screen.getByText("A", { exact: true })).toBeVisible();
  await expect(screen.getByText("B", { exact: true })).toBeVisible();
  await expect(screen.getByText("AB", { exact: true })).toBeHidden();
});
