/// <reference lib="dom" />
import { spawn } from "node:child_process";
import { mkdtemp, mkdir } from "node:fs/promises";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Peer refusal shows the complete headless setup instruction", WEB, async ({ t3, app, browser, screen }) => {
  await mkdir("/tmp/factory-issue-49641-evidence-1/peer", { recursive: true });
  const home = await mkdtemp("/tmp/factory-issue-49641-evidence-1/peer/run-");
  const peer = spawn(process.execPath, ["apps/server/src/bin.ts", "serve", "--base-dir", home, "--port", "47123", "--host", "127.0.0.1"], { cwd: APP_DIR, env: { ...process.env, T3CODE_DEV_SEED: "0" }, stdio: ["ignore", "pipe", "pipe"] });
  try {
    const token = await new Promise<string>((resolve, reject) => {
      let output = "";
      const timer = setTimeout(() => reject(new Error("Peer did not announce pairing URL")), 60000);
      peer.stdout.on("data", chunk => { output += chunk; const match = output.match(/(?:pair#token=)([A-Za-z0-9._~-]+)/); if(match) { clearTimeout(timer); resolve(match[1]!); } });
      peer.on("exit", code => { clearTimeout(timer); reject(new Error(`Peer exited ${code}: ${output}`)); });
    });
    await t3.project("demo");
    await t3.open("/settings/labs");
    await screen.getByRole("switch", "Linked environments", { exact: true }).tap();
    await t3.open("/settings/connections");
    await screen.getByRole("button", /^Link .* to another machine$/).tap();
    await screen.getByRole("textbox", "Address", { exact: true }).fill("http://127.0.0.1:47123");
    await screen.getByRole("textbox", "Pairing code", { exact: true }).fill(token);
    await screen.getByRole("button", "Link", { exact: true }).tap();
    await screen.getByText("Could not link the environment", { exact: true }).waitFor();
    await screen.getByRole("textbox", "Pairing code", { exact: true }).fill("");
    await browser.evaluate(() => { for (const a of document.getAnimations()) if(Number.isFinite(a.effect?.getComputedTiming().endTime)) a.finish(); return null; });
    await app.screenshot("peer-link-error");
    const description = await browser.evaluate(() => {
      const p = [...document.querySelectorAll<HTMLElement>('[data-slot="toast-description"]')].find(p => p.textContent?.includes("Linked environments is off"));
      return p ? { text: p.textContent, clipped: p.scrollHeight > p.clientHeight + 1 } : null;
    });
    expect(description?.text).toContain('"linkedEnvironmentsEnabled": true');
    expect(description?.text).toContain("userdata/settings.json");
    expect(description?.clipped, "The complete setup explanation is readable without copying").toBe(false);
  } finally { peer.kill("SIGTERM"); await new Promise(resolve => peer.once("exit", resolve)); }
});
