import { execFileSync } from "node:child_process";
import { readFileSync, realpathSync } from "node:fs";
import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Undoing an offline settle preserves the queued snooze through reconnection", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("proj");
  const thread = await t3.thread({ project, title: "go", messages: ["go"], model: "command-output" });
  await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" });
  await browser.addInitScript(() => {
    const sockets: WebSocket[] = [];
    let offline = false;
    const Native = window.WebSocket;
    window.WebSocket = class extends Native {
      constructor(url: string | URL, protocols?: string | string[]) {
        super(offline && new URL(String(url), location.href).pathname === "/ws" ? "ws://127.0.0.1:1/ws" : url, protocols);
        if (new URL(String(url), location.href).pathname === "/ws") sockets.push(this);
      }
    };
    (window as any).disconnectScenario = () => { offline = true; for (const socket of sockets) socket.close(); };
    (window as any).reconnectScenario = () => { offline = false; };
  });
  await t3.open(thread);
  await screen.getByText("The command printed one JSON line.").first().waitFor();
  await screen.getByText("Syncing messages...", { exact: false }).waitFor({ state: "hidden" });
  await app.screenshot("1-connected-done");
  const runtime = JSON.parse(readFileSync(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const port = new URL(runtime.origin).port;
  const owner = execFileSync("ss", ["-H", "-ltnp", `sport = :${port}`], { encoding: "utf8" });
  const pid = Number(/pid=(\d+)/.exec(owner)?.[1]);
  if (!pid || !realpathSync(`/proc/${pid}/cwd`).startsWith(realpathSync(APP_DIR))) throw new Error("Server port owner is outside this scenario checkout");
  await browser.route("**/api/auth/websocket-ticket", route => route.abort());
  try {
    await browser.evaluate(() => (window as any).disconnectScenario());
    await screen.getByText(/Scenario is reconnecting/).first().waitFor();
    process.kill(pid, "SIGSTOP");
    await screen.getByRole("button", "go, proj", { exact: true }).hover();
    await screen.getByRole("button", "Snooze thread", { exact: true }).tap();
    await screen.getByRole("menuitem", /Tomorrow/).tap();
    await screen.getByRole("button", "Snoozed 1", { exact: true }).tap();
    await screen.getByRole("button", /^go,/).tap();
    await app.screenshot("2-offline-snooze-pending");
    await screen.getByRole("button", "Thread actions for go").tap();
    await screen.getByRole("menuitem", "Settle thread", { exact: true }).tap();
    await screen.getByRole("button", /to undo/).tap();
    await screen.getByRole("button", /to undo/).waitFor({ state: "hidden" });
    await screen.getByRole("button", /^go,/).tap();
    await app.screenshot("3-offline-after-undo");
    const queued = await browser.evaluate(() => JSON.parse(localStorage.getItem("t3code:thread-triage-outbox") ?? '{"entries":[]}'));
    process.kill(pid, "SIGCONT");
    await browser.evaluate(() => (window as any).reconnectScenario());
    await browser.unroute("**/api/auth/websocket-ticket");
    await screen.getByRole("button", "Retry now", { exact: true }).tap();
    await screen.getByText(/Scenario is reconnecting/).first().waitFor({ state: "hidden" });
    await screen.getByText("Pending", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot("4-reconnected-snooze");
    expect(queued.entries.length, "Undo restores the queued snooze").toBe(1);
    await expect(screen.getByText("Snoozed", { exact: true }).first()).toBeVisible();
  } finally {
    process.kill(pid, "SIGCONT");
    await browser.evaluate(() => (window as any).reconnectScenario());
    await browser.unroute("**/api/auth/websocket-ticket");
  }
});
