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

// A real peer, bound only to IPv4 loopback. Both revisions use this same setup.
test("Mapped IPv4 loopback is shown as This device", WEB, async ({ t3, app, screen, browser }) => {
  const home = mkdtempSync("/tmp/factory-pr-28975-a1794656426-evidence-1/peer-");
  mkdirSync(`${home}/bin`);
  writeFileSync(`${home}/bin/hostnamectl`, '#!/bin/sh\necho "Loopback peer"\n', { mode: 0o755 });
  const peer = spawn(process.execPath, ["apps/server/src/bin.ts", "serve", "--host", "127.0.0.1", "--port", "39731", "--base-dir", home], {
    cwd: APP_DIR,
    env: { ...process.env, PATH: `${home}/bin:${process.env.PATH}`, T3CODE_DEV_SEED: "0", T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0" },
    stdio: ["ignore", "pipe", "pipe"],
  });
  let output = "";
  peer.stderr.on("data", () => {});
  try {
    await new Promise<void>((resolve, reject) => {
      peer.stdout.on("data", chunk => {
        output += chunk.toString();
        if (/pairingUrl:|Pairing URL:/.test(output)) resolve();
      });
      peer.once("exit", code => reject(new Error(`Peer exited ${code}`)));
    });
    const mapped = "http://[::ffff:7f00:1]:39731";
    for (const host of [mapped, "http://127.0.0.1:39731"]) {
      const response = await fetch(`${host}/.well-known/t3/environment`);
      if (response.status !== 200) throw new Error(`Loopback peer unreachable: ${response.status}`);
    }
    const paired = execFileSync(process.execPath, ["apps/server/src/bin.ts", "auth", "pairing", "create", "--base-dir", home, "--json"], { cwd: APP_DIR, encoding: "utf8" });
    const credential = JSON.parse(paired);
    await t3.project("Loopback demonstration");
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    await screen.getByLabel("Host").fill(mapped);
    await browser.evaluate(() => { const inputs = document.querySelectorAll('input'); for (const input of inputs) if (input.placeholder === "PAIRCODE") input.type = "password"; });
    await screen.getByLabel("Pairing code").fill(credential.credential);
    await screen.getByRole("dialog").getByRole("button", "Add environment").tap();
    await screen.getByRole("button", "Routes").last().tap();
    await screen.getByText("In use").waitFor();
    await screen.getByRole("button", "Dismiss notification").tap();
    await screen.getByText("Backend added").waitFor({ state: "hidden" });
    await app.screenshot("mapped-loopback-route");
    await expect(screen.getByRole("list", "Routes to Loopback peer, preferred first")).toContainText("This device");
  } finally {
    peer.kill("SIGTERM");
    await once(peer, "exit");
  }
});
