/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Unreadable initial server configuration stops automatic retries", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Configuration demo");
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    await makeState(SECOND_HOME).state.project("Remote demo");
    await browser.addInitScript((host) => {
      const requests = new WeakMap<WebSocket, string>();
      const frames = new WeakMap<Event, string>();
      let attempts = 0;
      let subscriptions = 0;
      let invalidUpdates = 0;
      let validSnapshots = 0;
      const send = WebSocket.prototype.send;
      WebSocket.prototype.send = function(data) {
        if (typeof data === "string" && this.url.startsWith(host.replace(/^http/, "ws"))) {
          for (const request of [JSON.parse(data)].flat()) {
            if (request?._tag === "Request" && request.tag === "subscribeServerConfig") {
              requests.set(this, String(request.id));
              subscriptions++;
              if (sessionStorage.getItem("corrupt-config") === "yes") attempts++;
            }
          }
        }
        return send.call(this, data);
      };
      const listen = WebSocket.prototype.addEventListener;
      WebSocket.prototype.addEventListener = function(type, listener, options) {
        if (type !== "message" || typeof listener !== "function") return listen.call(this, type, listener, options);
        return listen.call(this, type, (event) => {
          const cached = frames.get(event);
          if (cached !== undefined) return listener.call(this, new MessageEvent("message", { data: cached }));
          const data = (event as MessageEvent).data;
          if (typeof data !== "string") return listener.call(this, event);
          const parsed = JSON.parse(data);
          let changed = false;
          for (const message of [parsed].flat()) {
            if (message?._tag !== "Chunk" || String(message.requestId) !== requests.get(this)) continue;
            for (const value of message.values) {
              if (value.type === "snapshot") {
                if (sessionStorage.getItem("corrupt-config") === "yes") { value.config.cwd = 42; changed = true; }
                else validSnapshots++;
              }
              if (value.type === "settingsUpdated" && sessionStorage.getItem("corrupt-update") === "yes") {
                value.payload.settings.sourceControlWritingStyle = 42;
                sessionStorage.removeItem("corrupt-update");
                invalidUpdates++;
                changed = true;
              }
            }
          }
          frames.set(event, JSON.stringify(parsed));
          return listener.call(this, changed ? new MessageEvent("message", { data: JSON.stringify(parsed) }) : event);
        }, options);
      } as typeof WebSocket.prototype.addEventListener;
      Object.assign(window, { configAttempts: () => attempts, updateStats: () => ({ subscriptions, invalidUpdates, validSnapshots }) });
    }, host);
    await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" });
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await browser.evaluate(() => {
      document.querySelector<HTMLInputElement>('input[placeholder="PAIRCODE"]')!.type = "password";
    });
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("button", "List", { exact: true }).tap();
    await screen.getByRole("button", "More actions for Scenario").waitFor({ timeout: 60000 });
    await browser.evaluate(() => sessionStorage.setItem("corrupt-config", "yes"));
    await app.open("/settings/connections");
    await screen.getByRole("button", "List", { exact: true }).tap();
    await runPromise(Effect.sleep("30 seconds"));
    const attempts = await browser.evaluate(() => {
      const count = (window as unknown as { configAttempts: () => number }).configAttempts();
      const panel = document.createElement("div");
      panel.textContent = `Frame fixture: snapshot.config.cwd = 42 | 30-second observation | Config subscriptions: ${count}`;
      panel.style.cssText = "position:fixed;bottom:16px;left:280px;z-index:9999;background:#111827;color:white;padding:16px;border:1px solid #64748b;border-radius:8px;font:14px monospace";
      document.body.append(panel);
      return count;
    });
    await app.screenshot("invalid-initial-config-after-30-seconds");
    expect.soft(attempts, "Exactly one config subscription, without automatic retries").toBe(1);
    await expect.soft(screen.getByText("Client not supported", { exact: false }).first()).toBeVisible();
    await expect.soft(screen.getByRole("switch", /Switch (on|off) Scenario/)).toHaveAttribute("aria-checked", "false");
    // Reload with valid frames, then inject exactly one unreadable later update.
    await browser.evaluate(() => sessionStorage.removeItem("corrupt-config"));
    const remoteId = (await (await fetch(`${host}/.well-known/t3/environment`)).json()).environmentId;
    await app.open(`/settings/source-control?machine=${remoteId}`);
    const credits = screen.getByRole("switch", "Remove agent credits when merging", { exact: true });
    await credits.waitFor({ timeout: 60000 });
    await browser.evaluate(() => sessionStorage.setItem("corrupt-update", "yes"));
    await credits.tap();
    await runPromise(Effect.sleep("10 seconds"));
    const update = await browser.evaluate(() => {
      const stats = (window as unknown as { updateStats: () => { subscriptions: number; invalidUpdates: number; validSnapshots: number } }).updateStats();
      const panel = document.createElement("div");
      panel.textContent = `One malformed settingsUpdated frame | Subscriptions: ${stats.subscriptions} | Invalid updates: ${stats.invalidUpdates} | Valid snapshots: ${stats.validSnapshots}`;
      panel.style.cssText = "position:fixed;bottom:16px;left:280px;z-index:9999;background:#111827;color:white;padding:12px;border:1px solid #64748b;border-radius:8px;font:12px monospace";
      document.body.append(panel);
      return stats;
    });
    await app.screenshot("later-update-reconnects-to-valid-snapshot");
    expect.soft(update.invalidUpdates).toBe(1);
    expect.soft(update.subscriptions).toBeGreaterThanOrEqual(2);
    expect.soft(update.validSnapshots).toBeGreaterThanOrEqual(2);
    await expect.soft(credits).toBeEnabled();
    await app.open("/settings/connections");
    await screen.getByRole("button", "List", { exact: true }).tap();
    await runPromise(Effect.sleep("3 seconds"));
    await app.screenshot("valid-frames-reload-recovery");
    await expect.soft(screen.getByText("Client not supported", { exact: false })).not.toBeVisible();
  } finally { await server.stop(); }
});
