import { spawn } from "node:child_process";
import { once } from "node:events";
import { mkdirSync, writeFileSync } from "node:fs";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Schedule from "effect/Schedule";
import * as GlobalFlag from "effect/cli/GlobalFlag";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NetService from "@t3tools/shared/Net";
import { withThreadTools } from "../../apps/server/src/cli/thread.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// Both machines are real servers; stopping and restarting B preserves its own fresh data.
test("Linked environment recovers after the peer wakes up", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Recovery demo");
  const origin = app.baseUrl!;
  const home = `${T3_HOME}-recovery-peer-${Date.now()}`;
  mkdirSync(`${home}/userdata`, { recursive: true });
  writeFileSync(`${home}/userdata/settings.json`, JSON.stringify({ linkedEnvironmentsEnabled: true }));
  const port = await runPromise(Effect.gen(function* () {
    return yield* (yield* NetService.NetService).reserveLoopbackPort();
  }).pipe(Effect.provide(NetService.layer)));
  const host = `http://127.0.0.1:${port}`;
  let child: ReturnType<typeof spawn> | undefined;
  const start = async () => {
    child = spawn(process.execPath, ["apps/server/src/bin.ts", "serve", "--base-dir", home,
      "--port", String(port), "--host", "127.0.0.1"], {
      cwd: APP_DIR, env: { ...process.env, T3CODE_DEV_SEED: "0", T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0",
        T3CODE_ENVIRONMENT_LABEL: "Recovery peer", T3CODE_ENVIRONMENT_MACHINE_KIND: "laptop" },
      stdio: ["ignore", "pipe", "pipe"],
    });
    child.stderr!.on("data", () => {});
    child.stdout!.on("data", () => {});
    await runPromise(environmentId(host).pipe(Effect.retry({ schedule: Schedule.spaced("100 millis"), times: 200 })));
    // The CLI reads the server's ready runtime file.
    await runPromise(makeState(home).cli(["environment", "list", "--json"]));
  };
  const stop = async () => {
    if (!child || child.exitCode !== null) return;
    const exited = once(child, "exit"); child.kill("SIGTERM"); await exited; child = undefined;
  };
  const call = (id: string) => runPromise(withThreadTools(
    { baseDir: Option.some(T3_HOME), json: true, clientLabel: "Recovery proof" },
    tools => tools.call("t3_project_list", { environmentId: id }, Schema.Unknown).pipe(
      Effect.map(() => "OK"), Effect.catch(error => Effect.succeed(`FAILED ${String(error.detail ?? error)}`)),
    ),
  ).pipe(Effect.provideService(GlobalFlag.LogLevel, Option.none()),
    Effect.provide([NodeCrypto.layer, NetService.layer])));
  const showLinks = async () => {
    await t3.open("/settings/connections#linked-environments");
    await browser.reload();
    await screen.getByRole("button", "List", { exact: true }).tap();
    await screen.getByRole("heading", "Recovery peer", { exact: true }).waitFor();
  };
  try {
    await start();
    await runPromise(Effect.gen(function* () {
      const primary = yield* rpcClient(T3_HOME, origin);
      yield* primary["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
      const pairing = yield* makeState(home).cli(["auth", "pairing", "create", "--json"]);
      const { credential } = JSON.parse(pairing.stdout);
      yield* primary["peerLinks.link"]({ url: host, pairingCode: credential, access: "full-access" });
    }).pipe(Effect.scoped));
    const id = await runPromise(environmentId(host));
    if (await call(id) !== "OK") throw new Error("Initial linked call failed");
    await showLinks();
    await app.screenshot("peer-before-outage");
    await stop();
    const failure = await call(id);
    if (!failure.includes("did not answer")) throw new Error(`Outage was not reproduced: ${failure}`);
    await showLinks();
    await screen.getByText(/Full access · (Recovery peer did not answer at|Not answering right now)/).waitFor();
    await app.screenshot("peer-during-outage");
    await start();
    await runPromise(environmentId(host));
    await runPromise(makeState(T3_HOME).cli(["environment", "list", "--json"]));
    await showLinks();
    await app.screenshot("peer-reachable-after-restart");
    const text = await browser.evaluate(() => document.body.innerText);
    expect(text.includes("did not answer"), "A reachable peer must not retain the outage error").toBe(false);
    expect(text.includes("Reachable"), "Recovered linked environment is reachable").toBe(true);
  } finally { await stop(); }
});
