import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Interrupted Send now stays silent", WEB, async ({ t3, app, screen, browser }) => {
  await browser.addInitScript(() => {
    const NativeWebSocket = window.WebSocket;
    const frames: Array<{ direction: string; data: string }> = [];
    (window as any).proofFrames = frames;
    window.WebSocket = class extends NativeWebSocket {
      constructor(url: string | URL, protocols?: string | string[]) {
        super(url, protocols);
        this.addEventListener("message", (event) => {
          const data = typeof event.data === "string" ? event.data : new TextDecoder().decode(event.data);
          frames.push({ direction: "received", data });
          const response = JSON.parse(data);
          const firstExits = ((window as any).proofFirstExits ??= {});
          if (response._tag === "Exit" && firstExits[response.requestId] === undefined) firstExits[response.requestId] = response.exit;
          const interrupted = firstExits[response.requestId] === response.exit && String(response.requestId) === String((window as any).proofInterruptedRequest) && response.exit?._tag === "Failure" && response.exit.cause?.every((c: any) => c._tag === "Interrupt");
          const error = interrupted ? { commandType: "queued-run.start", message: "Server returned an interruption-only cause." } : null;
          if (error) {
            (window as any).proofFailure = error;
            const panel = document.createElement("pre");
            panel.id = "proof-wire";
            panel.style.cssText = "position:fixed;left:12px;top:290px;width:218px;white-space:pre-wrap;z-index:2147483647;padding:10px;background:#18212b;color:#fff;font:12px/1.5 monospace;border:2px solid #7b9bbd;border-radius:8px";
            panel.textContent = "DRIVER: live server response\n\n" + error.commandType + "\n→ Interrupted\n\n" + error.message.replace(/Target run .*? is /, "Target run is ");
            document.body.append(panel);
            (window as any).proofFailureResolve?.(true);
          }
        });
      }
      send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {
        const request = JSON.parse(typeof data === "string" ? data : new TextDecoder().decode(data as ArrayBuffer));
        if ((window as any).proofCancelNext && request.payload?.type === "queued-run.start") {
          (window as any).proofCancelNext = false;
          (window as any).proofInterruptedRequest = request.id;
          super.send(data);
          super.send(JSON.stringify({ _tag: "Interrupt", requestId: request.id }));
          return;
        }
        frames.push({ direction: "sent", data: typeof data === "string" ? data : new TextDecoder().decode(data as ArrayBuffer) });
        return super.send(data);
      }
    };
    new MutationObserver(() => {
      if (!document.body) return;
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      let node;
      while ((node = walker.nextNode())) {
        if (node.textContent?.match(/\/(?:home|Users)\//)) node.textContent = node.textContent.replace(/\/(?:home|Users)\/[^\s)]+/g, "[workspace]");
      }
    }).observe(document, { childList: true, subtree: true, characterData: true });
  });
  const project = await t3.project("queue-demo");
  const thread = await t3.thread({ project, title: "Queued message retry", messages: ["Hello"], model: "showcase" });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Run sleep 600, then reply done.");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByRole("button", "Stop generation").waitFor({ state: "visible" });
  await screen.getByText("The user wants a short tour", { exact: false }).last().waitFor({ state: "visible" });
  await screen.getByRole("textbox").fill("Follow-up: reply with the result.");
  await screen.getByRole("textbox").press("Control+Enter");
  await screen.getByRole("button", "Send now", { exact: true }).waitFor({ state: "visible" });
  await app.screenshot("queued-before-stop");
  await screen.getByRole("button", "Stop generation").tap();
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  await browser.evaluate(() => { (window as any).proofCancelNext = true; return true; });
  await screen.getByRole("button", "Send now", { exact: true }).tap();
  await browser.evaluate(() => (window as any).proofFailure ? true : new Promise((resolve, reject) => {
    (window as any).proofFailureResolve = resolve;
    setTimeout(() => reject(new Error("No actual RPC interruption observed")), 5000);
  }));
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
  console.log("WIRE", await browser.evaluate(() => (window as any).proofFrames.filter((f: any) => /promote|stopping|queued-run|Failure|run.stop/.test(f.data))));
  await new Promise((resolve) => setTimeout(resolve, 600));
  await app.screenshot("send-now-rejection");
  await expect(screen.getByText("Could not send queued message", { exact: true })).toBeHidden();

});
