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

test("Thread find excludes hidden CR-only alert markers and keeps visible bodies", WEB, async ({ t3, app, screen, browser }) => {
  const fixture = `${APP_DIR}/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson`;
  const replies = ["> [!NOTE]\r> hi", "> [!NOTE]\r> **Bold** body.", "> [!NOTE]\n> hi"];
  const recording = replies.flatMap(text => [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: {} } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", 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");
  const runtime = `${T3_HOME}/userdata/server-runtime.json`;
  const previous = await readFile(runtime, "utf8");
  const restarted = new Promise<void>((resolve, reject) => {
    const watcher = watch(`${T3_HOME}/userdata`, async (_event, name) => {
      if (name !== "server-runtime.json") return;
      try {
        const next = await readFile(runtime, "utf8");
        if (next !== previous) { watcher.close(); resolve(); }
      } catch { /* The runtime file is replaced while the server restarts. */ }
    });
    watcher.on("error", reject);
  });
  await writeFile(fixture, recording);
  await restarted;
  const project = await t3.project("alert-search-demo");
  const thread = await t3.thread({ project, title: "CR and LF alert search", model: "multi-turn", messages: ["Plain CR alert", "Inline CR alert", "LF control"] });
  await t3.open(thread);
  await screen.getByText("Bold", { exact: true }).waitFor();
  await browser.keyboard.press("Control+f");
  const find = screen.getByRole("searchbox", "Find in thread");
  const count = () => browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""');
  await find.fill("hi");
  await expect.poll(count).toBe("1/2");
  await app.screenshot("visible-body-search");
  await find.fill("[!NOTE]");
  try {
    await expect.poll(count, { message: "Hidden alert markers have no thread-find matches" }).toBe("0/0");
  } finally {
    await app.screenshot("hidden-marker-search");
  }
});
