// A second T3 server for scenarios that need another machine: its own T3 home, the replay
// agent, and a pairing token for Settings > Connections > Add environment.
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as NetService from "@t3tools/shared/Net";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Path from "effect/Path";

import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";
import { ScenarioError } from "./shell.ts";
import { prepareHome, SCENARIO_MACHINE_ENV, start } from "./start-app.ts";

const SECOND_HOME = `${T3_HOME}-route-learning`;

/** A second server on its own T3 home, running until interrupted. `--dev-url` admits the web
 * origin through CORS and registers the replay agent; `paired` gets the Add environment input. */
const runSecondServer = Effect.fn("scenario.secondServer")(function* (
  devUrl: string,
  paired: (target: { readonly host: string; readonly token: string }) => void,
) {
  const path = yield* Path.Path;
  const node = yield* HostProcess.ExecutablePath;
  const hostEnvironment = yield* HostProcess.Environment;
  const port = yield* (yield* NetService.NetService).reserveLoopbackPort();
  yield* prepareHome(SECOND_HOME);
  const token = yield* Deferred.make<string>();
  const server = yield* start({
    cwd: APP_DIR,
    command: node,
    args: [
      "apps/server/src/bin.ts",
      "serve",
      "--host",
      "0.0.0.0",
      "--port",
      String(port),
      "--base-dir",
      SECOND_HOME,
      "--dev-url",
      devUrl,
    ],
    env: {
      PATH: `${path.join(SECOND_HOME, "bin")}:${hostEnvironment.PATH ?? ""}`,
      HOME: hostEnvironment.HOME,
      T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0",
      T3CODE_DEV_SEED: "0",
      ...SCENARIO_MACHINE_ENV,
    },
    onLine: (line) => {
      const value = /^Token:\s*(\S+)/.exec(line)?.[1];
      return value === undefined ? Effect.void : Deferred.succeed(token, value).pipe(Effect.asVoid);
    },
  });
  // A server that exits before printing its token never will: fail instead of waiting forever.
  const exited = server.exitCode.pipe(
    Effect.flatMap(
      (code) =>
        new ScenarioError({ message: `The second server exited with code ${code} at startup.` }),
    ),
  );
  paired({
    host: `http://127.0.0.1:${port}`,
    token: yield* Effect.raceFirst(Deferred.await(token), exited),
  });
  return yield* Effect.never;
});

/** Starts the second server for the web app at `devUrl`. `ready` settles with its pairing input. */
function startSecondServer(devUrl: string) {
  const pairing = Promise.withResolvers<{ readonly host: string; readonly token: string }>();
  const server = Effect.runFork(
    runSecondServer(devUrl, pairing.resolve).pipe(
      Effect.scoped,
      Effect.provide([NodeServices.layer, NetService.layer]),
    ),
  );
  server.addObserver((exit) =>
    pairing.reject(
      Exit.isFailure(exit) ? Cause.squash(exit.cause) : new Error("The second server stopped."),
    ),
  );
  return { ready: pairing.promise, stop: () => Effect.runPromise(Fiber.interrupt(server)) };
}


// Passive wire observer: forwards every real frame unchanged. The on-screen table
// exposes starts and interruptions that otherwise have no visible UI symptom.
test("Learning a real host route keeps durable subscriptions alive", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("demo");
  await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" });
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    await t3.open("/settings/connections");
    await screen.getByRole("button", "List", { exact: true }).tap();
    await browser.evaluate((host) => {
      const native = window.WebSocket;
      const watched = new URL(host).port;
      const tags = ["subscribeServerConfig", "subscribeProjectClones", "subscribeDeviceState", "subscribeAuthAccess", "orchestration.subscribeShell"];
      const state = { sockets: 0, starts: Object.fromEntries(tags.map(tag => [tag, 0])), interrupts: Object.fromEntries(tags.map(tag => [tag, 0])), learnedEndpoints: 0, events: [] as string[] };
      (window as any).__durableProof = state;
      const render = () => {
        let panel = document.getElementById("durable-wire-proof");
        if (!panel) {
          panel = document.createElement("section");
          panel.id = "durable-wire-proof";
          panel.style.cssText = "position:fixed;bottom:20px;right:20px;width:620px;background:#111827;color:#f9fafb;border:1px solid #64748b;border-radius:12px;padding:20px;z-index:99999;font:15px/1.6 monospace;box-shadow:0 8px 40px #0008";
          document.body.append(panel);
        }
        panel.innerHTML = `<strong>LIVE WEBSOCKET OBSERVER · HOST B</strong><br>Real frames forwarded unchanged<br>Sockets opened: ${state.sockets} · Advertised endpoints: ${state.learnedEndpoints}<table style="width:100%;margin-top:12px;text-align:left"><tr><th>Subscription</th><th>Starts</th><th>Interrupts</th></tr>${tags.map(tag => `<tr><td>${tag.replace("orchestration.", "")}</td><td>${state.starts[tag]}</td><td>${state.interrupts[tag]}</td></tr>`).join("")}</table><div style="border-top:1px solid #64748b;margin-top:12px;padding-top:10px">${state.events.slice(-6).join("<br>") || "Waiting for pairing…"}</div>`;
      };
      window.WebSocket = class extends native {
        private watched = false;
        private requests = new Map<string, string>();
        constructor(url: string | URL, protocols?: string | string[]) {
          super(url, protocols);
          this.watched = new URL(String(url)).port === watched;
          if (this.watched) {
            state.sockets++;
            this.addEventListener("message", (event) => {
              try {
                const frame = JSON.parse(String(event.data));
                const frames = Array.isArray(frame) ? frame : [frame];
                for (const item of frames) {
                  if (this.requests.get(String(item.requestId)) === "subscribeServerConfig") {
                    const text = JSON.stringify(item);
                    const matches = text.match(/"directEndpoints":\[(.*?)\]/);
                    if (matches) {
                      state.learnedEndpoints = (matches[1].match(/httpBaseUrl/g) ?? []).length;
                      state.events.push(`Received server config: ${state.learnedEndpoints} real endpoint(s)`);
                    }
                  }
                }
              } catch {}
              render();
            });
          }
        }
        override send(data: Parameters<WebSocket["send"]>[0]) {
          if (this.watched && typeof data === "string") {
            try {
              const frame = JSON.parse(data);
              for (const item of Array.isArray(frame) ? frame : [frame]) {
                if (item._tag === "Request" && tags.includes(item.tag)) {
                  this.requests.set(String(item.id), item.tag);
                  state.starts[item.tag]++;
                  state.events.push(`START ${item.tag.replace("orchestration.", "")}`);
                }
                if (item._tag === "Interrupt") {
                  const tag = this.requests.get(String(item.requestId));
                  if (tag) { state.interrupts[tag]++; state.events.push(`INTERRUPT ${tag.replace("orchestration.", "")}`); }
                }
              }
            } catch {}
            render();
          }
          super.send(data);
        }
      };
    }, host);
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog", "Add Environment", { exact: true });
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await dialog.waitFor({ state: "hidden" });
    await screen.getByText("2 routes", { exact: true }).waitFor({ timeout: 60_000 });
    // Observe the same quiet interval on both commits, including any immediate restart.
    await new Promise(resolve => setTimeout(resolve, 5000));
    await app.screenshot("after-route-learning");
    const state = await browser.evaluate(() => (window as any).__durableProof);
    console.log("Durable subscriptions observed:", JSON.stringify(state));
    expect(state.starts.subscribeProjectClones).toBe(1);
    expect(state.starts.subscribeDeviceState).toBe(1);
    expect(state.starts.subscribeAuthAccess).toBe(1);
    expect(state.starts["orchestration.subscribeShell"]).toBe(1);
    expect(state.interrupts.subscribeProjectClones).toBe(0);
    expect(state.interrupts.subscribeDeviceState).toBe(0);
    expect(state.interrupts.subscribeAuthAccess).toBe(0);
    expect(state.interrupts["orchestration.subscribeShell"]).toBe(0);
  } finally {
    await server.stop();
  }
});
