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

test("A picker selection wins over an earlier slow chat file lookup", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("file-race-demo", {
    "notes/cited-note.txt": "CITED FILE — the earlier chat lookup must not replace the picker selection.\n",
    "picker-note.txt": "PICKER FILE — this newer selection should remain active.\n",
  });
  const recording = `${APP_DIR}/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson`;
  const original = await readFile(recording, "utf8");
  let thread;
  try {
    await writeFile(recording, original.replaceAll("first fixture turn complete", "Please review [Cited note](cited-note.txt)."));
    await new Promise(resolve => setTimeout(resolve, 4000));
    thread = await t3.thread({ project, title: "File selection race", messages: ["Review the cited note"] });
  } finally { await writeFile(recording, original); await new Promise(resolve => setTimeout(resolve, 4000)); }
  await browser.addInitScript(() => {
    const originalSend = WebSocket.prototype.send;
    const originalAdd = WebSocket.prototype.addEventListener;
    const state = { id: "", held: [] as (() => void)[] };
    (window as any).__slowLookup = state;
    (window as any).__releaseLookup = () => { for (const deliver of state.held.splice(0)) deliver(); };
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") {

        try { const request = JSON.parse(data); if (data.includes("cited-note.txt") && data.includes("projects.searchEntries")) state.id = String(request.id); } catch {}
      }
      return originalSend.call(this, data);
    };
    WebSocket.prototype.addEventListener = function(type: any, listener: any, options: any) {
      if (type !== "message" || typeof listener !== "function") return originalAdd.call(this, type, listener, options);
      return originalAdd.call(this, type, function(this: WebSocket, event: MessageEvent) {
        const deliver = () => listener.call(this, event);

        let response; try { response = JSON.parse(event.data); } catch {}
        if (state.id && String(response?.requestId) === state.id) state.held.push(deliver);
        else deliver();
      }, options);
    } as any;
  });
  await t3.open(thread);
  await screen.getByRole("link", "cited-note.txt", { exact: true }).tap();
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("picker-note.txt");
  await screen.getByRole("option", "picker-note.txt", { exact: false }).tap();
  await screen.getByText("PICKER FILE", { exact: false }).waitFor();
  await app.screenshot("picker-selected");
  const diagnostics = await browser.evaluate(() => ({ id: (window as any).__slowLookup.id, held: (window as any).__slowLookup.held.length }));

  if (!diagnostics.held) throw new Error("Slow lookup response was not held");
  await browser.evaluate(() => { (window as any).__releaseLookup(); });
  await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 1500)));
  await app.screenshot("lookup-finished");
  await expect(screen.getByText("PICKER FILE", { exact: false })).toBeVisible();
});
