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 reply = "See [report.md](<C:%5CUsers%5Ctest%5Creport.md#L7>) for details.";

test("Find counts an assistant's percent-encoded Windows file chip", 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 transcript = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: reply } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map(x => JSON.stringify(x)).join("\n");
  const project = await t3.project("file-review");
  let thread;
  try {
    await writeFile(fixture, transcript);
    thread = await t3.thread({ project, title: "Windows file review", messages: ["Reply with exactly this text: `" + reply + "`"], model: "showcase" });
  } finally {
    await writeFile(fixture, original);
  }
  await t3.open(thread);
  await screen.getByRole("link", "report.md · L7").waitFor();
  await browser.keyboard.press("Control+f");
  await screen.getByRole("searchbox", "Find in thread").fill("report.md · L7");
  try {
    await expect.poll(() => browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""'), { message: "Find counts the assistant file chip including its line number" }).toBe("1/1");
  } finally {
    await app.screenshot("encoded-windows-chip-find");
  }
});
