/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Thread search uses visible link labels, excluding angle addresses and quoted titles", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Writing");
  const otherProject = await t3.project("Reading");
  const notes = await t3.thread({ project, title: "Tighten Notes Wording", messages: ["Start"] });
  const guide = await t3.thread({ project: otherProject, title: "Reading list", messages: ["Start"] });
  // Observe completion of the real search RPC without changing requests or responses.
  await browser.addInitScript(() => {
    const queries = new Map<string, string>();
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") for (const request of [JSON.parse(data)].flat()) {
        if (request?._tag === "Request" && request.tag === "orchestration.searchThreads") {
          queries.set(String(request.id), request.payload.query);
        }
      }
      return send.call(this, data);
    };
    const listen = WebSocket.prototype.addEventListener;
    WebSocket.prototype.addEventListener = function(this: WebSocket, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) {
      if (type !== "message" || typeof listener !== "function") return listen.call(this, type, listener, options);
      return listen.call(this, type, (event: Event) => {
        listener.call(this, event);
        const data = (event as MessageEvent).data;
        if (typeof data === "string") for (const response of [JSON.parse(data)].flat()) {
          if (response?._tag === "Exit" && queries.has(String(response.requestId))) {
            document.documentElement.dataset.searchAnswered = queries.get(String(response.requestId));
          }
        }
      }, options);
    } as typeof WebSocket.prototype.addEventListener;
  });
  await t3.open(notes);
  await screen.getByRole("textbox").pressSequentially("Can you tighten the wording in [notes.md](</Users/me/Bittern Notes/notes.md>) before we ship?");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  await t3.open(guide);
  await screen.getByRole("textbox").pressSequentially('Read [the guide](https://x.dev/a "Bittern guide").');
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("second fixture turn complete", { exact: false }).waitFor();
  await app.screenshot("rendered-guide-message");
  await browser.keyboard.press("Control+k");
  const palette = screen.getByRole("dialog", "Command palette");
  const results: Record<string, string> = {};
  for (const query of ["notes.md", "the guide", "bittern", "x.dev"]) {
    await palette.getByRole("combobox").fill(query);
    await browser.locator(`html[data-search-answered="${query}"]`).waitFor({ state: "attached" });
    await palette.getByText("Searching messages…", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot(`search-${query.replaceAll(".", "-").replaceAll(" ", "-")}`);
    results[query] = await palette.textContent() ?? "";
  }
  expect(results["notes.md"]).toContain("notes.md before we ship?");
  expect(results["notes.md"]).not.toContain("Bittern Notes");
  expect(results["the guide"]).toContain("Read the guide.");
  expect(results["the guide"]).not.toContain("x.dev");
  expect(results["bittern"]).not.toContain("In messages");
  expect(results["x.dev"]).not.toContain("In messages");
});
