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

test("Send now explains a stop-race rejection and allows retry", 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 error = response.exit?.cause?.find((c: any) => c.error?.commandType === "queued-message.promote-to-steer")?.error;
          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→ Failure\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) {
        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 browser.evaluate(async () => {
    const stop = document.querySelector<HTMLButtonElement>('button[aria-label="Stop generation"]');
    const send = Array.from(document.querySelectorAll('button')).find((b) => b.textContent?.trim() === "Send now");
    if (!stop || !send) throw new Error("Stop or Send now not found");
    stop.click();
    await new Promise((resolve) => setTimeout(resolve, 0));
    send.click();
    return true;
  });
  await browser.evaluate(() => (window as any).proofFailure ? true : new Promise((resolve, reject) => {
    (window as any).proofFailureResolve = resolve;
    setTimeout(() => reject(new Error("No real steering rejection 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 screen.getByRole("button", "Send now", { exact: true }).tap();
  await screen.getByRole("button", "Send now", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("retry");
  await expect(screen.getByText("Could not send queued message", { exact: true })).toBeVisible();
});
