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

test("Launch, queued Send now and steering survive dropped sockets", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("demo-project");
  await browser.addInitScript(() => {
    const addListener = WebSocket.prototype.addEventListener;
    WebSocket.prototype.addEventListener = function(type, listener, options) {
      if (type === "message" && typeof listener === "function") {
        return addListener.call(this, type, function(event) {
          if (!(this as WebSocket & { scenarioBlockReplies?: boolean }).scenarioBlockReplies) listener.call(this, event);
        }, options);
      }
      return addListener.call(this, type, listener, options);
    };
    const scrub = () => {
      const walker = document.createTreeWalker(document.body ?? document.documentElement, NodeFilter.SHOW_TEXT);
      while (walker.nextNode()) {
        const node = walker.currentNode;
        if (node.parentElement?.closest("script,style")) continue;
        if (node.textContent?.includes("/home/")) node.textContent = node.textContent.replace(/\/home\/[^\s`<>]+/g, "[workspace path]");
      }
    };
    document.addEventListener("DOMContentLoaded", () => {
      scrub();
      new MutationObserver(scrub).observe(document.body, { childList: true, subtree: true, characterData: true });
    });
  });
  await t3.open();
  const outcomes = [];
  for (const delivery of ["lost-request", "lost-acknowledgement"]) {
    if (delivery === "lost-acknowledgement") await screen.getByRole("button", "New thread", { exact: true }).tap();
    await browser.evaluate((delivery) => {
      const original = WebSocket.prototype.send;
      let dropped = false;
      const attempts: string[] = [];
      const previous = document.getElementById("socket-proof");
      previous?.remove();
      const panel = document.createElement("div");
      panel.id = "socket-proof";
      panel.style.cssText = "position:fixed;top:8px;left:340px;z-index:99999;background:#172554;color:white;padding:12px;font:14px monospace;max-width:800px";
      panel.textContent = `Socket fault armed: ${delivery}`;
      document.body.append(panel);
      WebSocket.prototype.send = function(data) {
        const text = typeof data === "string" ? data : "";
        if (text.includes("orchestration.launchThread")) {
          const id = text.match(/\"commandId\":\"([^\"]+)/)?.[1] ?? "unknown";
          attempts.push(id);
          panel.dataset.attempts = JSON.stringify(attempts);
          panel.textContent = `${delivery} | launch attempts: ${attempts.length} | command IDs: ${attempts.join(", ")}`;
          if (!dropped) {
            dropped = true;
            if (delivery === "lost-acknowledgement") {
              Object.defineProperty(this, "scenarioBlockReplies", { value: true });
              original.call(this, data);
              setTimeout(() => this.close(4000, "Scenario lost acknowledgement"), 500);
            } else {
              this.close(4000, "Scenario transient socket loss");
            }
            return;
          }
        }
        return original.call(this, data);
      };
    }, delivery);
    const message = `Preserve first message after ${delivery}`;
    await screen.getByRole("textbox").fill(message);
    await screen.getByRole("textbox").press("Enter");
    await browser.evaluate(() => new Promise<null>(resolve => setTimeout(() => resolve(null), 10000)));
    await app.screenshot(delivery);
    const attempts = await browser.evaluate(() => JSON.parse(document.getElementById("socket-proof")?.dataset.attempts ?? "[]") as string[]);
    outcomes.push({ delivery, composer: await screen.getByRole("textbox").inputValue(), messages: await browser.locator("[data-user-message-body]").filter({ hasText: message }).count(), attempts: attempts.length, uniqueIds: new Set(attempts).size });
  }
  const project = await t3.project("queue-demo", { "src/math.ts": "export const sum = 1 + 1;\n" });
  const thread = await t3.thread({ project, title: "Queue socket recovery", model: "showcase", messages: ["Prepare a replay thread"] });
  await t3.open(thread);
  const arm = async (target: string) => {
    await browser.evaluate((target) => {
      const original = WebSocket.prototype.send;
      let dropped = false;
      const attempts: string[] = [];
      let panel = document.getElementById("socket-proof");
      if (!panel) {
        panel = document.createElement("div");
        panel.id = "socket-proof";
        panel.style.cssText = "position:fixed;top:8px;left:340px;z-index:99999;background:#172554;color:white;padding:12px;font:14px monospace;max-width:800px";
        document.body.append(panel);
      }
      panel.textContent = `Socket fault armed: ${target}`;
      WebSocket.prototype.send = function(data) {
        const text = typeof data === "string" ? data : "";
        if (text.includes(target)) {
          const id = text.match(/\"commandId\":\"([^\"]+)/)?.[1] ?? "unknown";
          attempts.push(id);
          panel!.dataset.attempts = JSON.stringify(attempts);
          panel!.textContent = `${target}: ${attempts.length} attempts | command IDs: ${attempts.join(", ")} | first request dropped before delivery`;
          if (!dropped) { dropped = true; this.close(4000, "Scenario transient socket loss"); return; }
        }
        return original.call(this, data);
      };
    }, target);
  };
  const settle = () => browser.evaluate(() => new Promise<null>(resolve => setTimeout(() => resolve(null), 3000)));
  const stop = screen.getByRole("button", "Stop generation");
  const composer = screen.getByRole("textbox");
  await composer.fill("Start a replay so I can queue work");
  await composer.press("Enter");
  await stop.waitFor({ state: "visible" });
  await composer.fill("Queued message to start immediately");
  await composer.press("Control+Enter");
  await screen.getByRole("button", "Send now").waitFor({ state: "visible" });
  await stop.tap();
  await screen.getByRole("button", "Resume thread").waitFor({ state: "visible" });
  await arm("queued-run.start");
  await screen.getByRole("button", "Send now").tap();
  await settle();
  await screen.getByText("Syncing messages...", { exact: false }).waitFor({ state: "hidden" });
  await app.screenshot("queued-start-after-reconnect");
  const startAttempts = await browser.evaluate(() => JSON.parse(document.getElementById("socket-proof")?.dataset.attempts ?? "[]") as string[]);
  const pausedStillQueued = await browser.evaluate(() => [...document.querySelectorAll("button")].some(b => b.textContent?.trim() === "Send now"));
  // Start another independent replay turn after the paused-queue observation.
  if (pausedStillQueued) await screen.getByRole("button", "Send now").tap();
  await stop.waitFor({ state: "hidden" });
  await composer.fill("Start a fresh replay for steering");
  await composer.press("Enter");
  await stop.waitFor({ state: "visible" });
  await composer.fill("Queued message to steer into the active turn");
  await composer.press("Control+Enter");
  await screen.getByRole("button", "Send now").waitFor({ state: "visible" });
  await arm("queued-message.promote-to-steer");
  await screen.getByRole("button", "Send now").tap();
  await browser.evaluate(() => new Promise<null>(resolve => setTimeout(() => resolve(null), 1500)));
  await app.screenshot("queued-steer-early");
  await browser.evaluate(() => new Promise<null>(resolve => setTimeout(() => resolve(null), 3000)));
  await screen.getByText("Syncing messages...", { exact: false }).waitFor({ state: "hidden" });
  await app.screenshot("queued-steer-after-reconnect");
  const steerAttempts = await browser.evaluate(() => JSON.parse(document.getElementById("socket-proof")?.dataset.attempts ?? "[]") as string[]);
  const steerStillQueued = await browser.evaluate(() => [...document.querySelectorAll("button")].some(b => b.textContent?.trim() === "Send now"));
  expect({ pausedStillQueued, steerStillQueued, startAttempts: startAttempts.length, steerAttempts: steerAttempts.length, startIds: new Set(startAttempts).size, steerIds: new Set(steerAttempts).size }).toEqual({ pausedStillQueued: false, steerStillQueued: false, startAttempts: 2, steerAttempts: 2, startIds: 1, steerIds: 1 });
  expect(outcomes).toEqual([
    { delivery: "lost-request", composer: "", messages: 1, attempts: 2, uniqueIds: 1 },
    { delivery: "lost-acknowledgement", composer: "", messages: 1, attempts: 2, uniqueIds: 1 },
  ]);
});
