/// <reference lib="dom" />
import { readFileSync, writeFileSync, watch } from "node:fs";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const REPLY = "See [src/main.ts#L10-L20](src/main.ts#L10-L20) and [src/main.ts#section](src/main.ts#section).\n\nControl [src/main.ts](src/main.ts) and [src/main.ts:10-20](src/main.ts#L10-L20).\n\nMismatch [src/main.ts#L11-L20](src/main.ts#L10-L20).";

test("Matching line-anchor labels render only the file chip", WEB, async ({ t3, app, browser, screen }) => {
  const fixture = `${APP_DIR}/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson`;
  const original = readFileSync(fixture, "utf8");
  const entries = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "fixture", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: REPLY } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ];
  let thread;
  try {
    const runtimeFile = `${T3_HOME}/userdata/server-runtime.json`;
    const initial = JSON.parse(readFileSync(runtimeFile, "utf8")).startedAt;
    const restarted = new Promise<void>((resolve) => {
      const watcher = watch(`${T3_HOME}/userdata`, () => {
        try {
          if (JSON.parse(readFileSync(runtimeFile, "utf8")).startedAt !== initial) {
            watcher.close();
            resolve();
          }
        } catch {}
      });
    });
    writeFileSync(fixture, entries.map((entry) => JSON.stringify(entry)).join("\n"));
    await restarted;
    const project = await t3.project("file-links", { "src/main.ts": "// example line\n".repeat(30) });
    thread = await t3.thread({ project, title: "File link labels", messages: ["Reply exactly with the matching line-anchor example, section anchor, control links, and mismatched line-anchor example." ] });
  await t3.open(thread);
  await screen.getByText(/^Mismatch/).first().waitFor();
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("file-anchor-labels");
  const text = await browser.evaluate(() => [...document.querySelectorAll(".chat-markdown")].map((node) => node.textContent).join("\n"));
  await browser.keyboard.press("Control+f");
  await screen.getByRole("searchbox", "Find in thread").fill("src/main.ts#L10-L20");
  try {
    await expect.poll(() => browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""')).toBe("0/0");
  } finally {
    await app.screenshot("line-anchor-thread-search");
  }
  expect(text).not.toContain("src/main.ts#L10-L20");
  expect(text).toContain("src/main.ts#section");
  expect(text).toContain("src/main.ts#L11-L20");
  } finally {
    writeFileSync(fixture, original);
  }
});
