import { expect } from "e2e";
import { spawn, execFileSync } from "node:child_process";
import { mkdirSync, openSync, appendFileSync } from "node:fs";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const sudo = (...args: string[]) => execFileSync("sudo", ["-n", ...args]);
const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
test("VPN pairing learns LAN and reconnects when VPN is off", WEB, async ({ t3, app, screen, browser }) => {
  const run = `/tmp/factory-pr-41054-evidence-1/run-${Date.now()}`;
  mkdirSync(run, { recursive: true });
  const home = `${run}/host`;
  const progress = (step: string) => appendFileSync(`${run}/progress.txt`, `${step}\n`);
  const vpn = "100.90.12.34";
  const port = "13779";
  let host: ReturnType<typeof spawn> | undefined;
  let iface = false, allow = false, block = false;
  try {
    sudo("ip", "link", "add", "nb41054", "type", "dummy"); iface = true;
    sudo("ip", "addr", "add", `${vpn}/32`, "dev", "nb41054");
    sudo("ip", "link", "set", "nb41054", "up");
    sudo("iptables", "-I", "INPUT", "1", "-i", "lo", "-s", vpn, "-d", vpn, "-p", "tcp", "-j", "ACCEPT"); allow = true;
    sudo("iptables", "-I", "OUTPUT", "1", "-d", "100.64.136.120", "-p", "tcp", "--dport", port, "-j", "REJECT"); block = true;
    host = spawn(process.execPath, ["apps/server/src/bin.ts", "--host", "0.0.0.0", "--port", port, "--base-dir", home, "--no-browser"], {
      cwd: APP_DIR, env: { ...process.env, T3CODE_DEV_SEED: "0", T3CODE_ENVIRONMENT_LABEL: "VPN host", T3CODE_ENVIRONMENT_MACHINE_KIND: "laptop", T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0" },
      stdio: ["ignore", openSync(`${run}/host.log`, "w"), openSync(`${run}/host-error.log`, "w")],
    });
    for (let i = 0; i < 120; i++) {
      try { if ((await fetch(`http://${vpn}:${port}/.well-known/t3/environment`, { signal: AbortSignal.timeout(1500) })).ok) break; } catch {}
      if (i === 119) throw new Error("Host did not start");
      await pause(500);
    }
    progress("host-ready");
    const pair = JSON.parse(execFileSync(process.execPath, ["apps/server/src/bin.ts", "auth", "pairing", "create", "--base-dir", home, "--json"], { cwd: APP_DIR, encoding: "utf8" }));
    progress("pairing-minted");
    const token = pair.credential ?? pair.token ?? pair.pairingToken;
    if (!token) throw new Error(`No credential; keys: ${Object.keys(pair)}`);
    progress("seeding");
    await t3.project("LAN fallback demo");
    progress("opening");
    await t3.open("/settings/connections");
    progress("adding-host");
    await screen.getByRole("button", "Add environment").tap();
    await screen.getByRole("textbox", "Host").fill(`http://${vpn}:${port}`);
    await browser.evaluate(() => { const el = document.querySelector('input[placeholder="PAIRCODE"]'); el?.setAttribute("type", "password"); });
    await screen.getByLabel("Pairing code").fill(token);
    await screen.getByRole("dialog").getByRole("button", "Add environment").tap();
    await screen.getByText("VPN host", { exact: true }).waitFor();
    await screen.getByRole("button", "List", { exact: true }).tap();
    const row = browser.locator('div.grid:has(> div > p)').filter({ hasText: "VPN host" });
    await pause(5000);
    await app.screenshot("paired-over-vpn");
    sudo("ip", "addr", "del", `${vpn}/32`, "dev", "nb41054");
    const lan = await fetch(`http://192.168.122.39:${port}/.well-known/t3/environment`);
    if (!lan.ok) throw new Error("LAN unavailable");
    await app.open("/settings/connections");
    await pause(30000);
    await screen.getByRole("button", "List", { exact: true }).tap();
    await row.getByRole("button", /routes/i).tap();
    await app.screenshot("vpn-off-lan-fallback");
    await expect(row).toContainText("Connected");
  } finally {
    if (host) { host.kill("SIGTERM"); await new Promise(resolve => host!.once("exit", resolve)); }
    if (block) sudo("iptables", "-D", "OUTPUT", "-d", "100.64.136.120", "-p", "tcp", "--dport", port, "-j", "REJECT");
    if (allow) sudo("iptables", "-D", "INPUT", "-i", "lo", "-s", vpn, "-d", vpn, "-p", "tcp", "-j", "ACCEPT");
    if (iface) sudo("ip", "link", "del", "nb41054");
  }
});
