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

test("Thread find counts file chips after bare anchor placeholders", WEB, async ({ t3, app, screen, browser }) => {
  const fixture = join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await readFile(fixture, "utf8");
  const replies = ["Use <a> for links.\n\nSee /Users/me/app.ts:42", "Use <a/> for links.\n\nSee /Users/me/app.ts:42", "Plain control.\n\nSee /Users/me/app.ts:42"];
  const transcript = replies.flatMap(text => [
    { 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 } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ]).map(row => JSON.stringify(row)).join("\n");
  await writeFile(fixture, transcript);
  try {
    const project = await t3.project("anchor-demo");
    const thread = await t3.thread({ project, title: "Bare anchor file links", model: "showcase", messages: ["first", "second", "third"] });
    await t3.open(thread);
    await screen.getByText("Plain control.", { exact: false }).waitFor();
    await browser.keyboard.press("Control+f");
    await screen.getByRole("searchbox", "Find in thread").fill("app.ts · L42");
    try {
      await expect.poll(() => browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""'), { message: "All three displayed file-chip labels are searchable" }).toBe("1/3");
    } finally {
      await app.screenshot("file-chips-after-bare-anchors");
      await browser.evaluate("new Promise(resolve => setTimeout(resolve, 2000))");
    }
  } finally {
    await writeFile(fixture, original);
  }
});
