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

test("Run on explains why a connected machine cannot host No project threads", WEB, async ({ t3, app, screen, browser }) => {
  execFileSync("git", ["init", "--quiet", T3_HOME.slice(0, T3_HOME.lastIndexOf("/"))]);
  const home = mkdtempSync("/tmp/factory-issue-34434-evidence-1/healthy-");
  mkdirSync(`${home}/userdata`);
  copyFileSync(`${T3_HOME}/userdata/settings.json`, `${home}/userdata/settings.json`);
  const log = openSync(`${home}/server.log`, "a");
  const child = spawn(process.execPath, ["apps/server/src/bin.ts", "serve", "--base-dir", home, "--port", "41877"], {
    cwd: APP_DIR,
    env: { ...process.env, T3CODE_DEV_SEED: "0", T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0", PATH: `${T3_HOME}/bin:${process.env.PATH}` },
    stdio: ["ignore", log, log],
  });
  try {
    for (let i = 0; i < 120; i++) {
      try { if ((await fetch("http://127.0.0.1:41877/.well-known/t3/environment")).ok) break; } catch {}
      await new Promise(r => setTimeout(r, 500));
    }
    const paired = execFileSync(process.execPath, ["apps/server/src/bin.ts", "auth", "pairing", "create", "--base-dir", home, "--base-url", "http://127.0.0.1:41877", "--json"], { cwd: APP_DIR, encoding: "utf8" });
    const pairing = JSON.parse(paired);
    await t3.project("Demo");
    await t3.open();
    await screen.getByText("Demo", { exact: true }).first().waitFor();
    await app.open("/settings/connections");
    await screen.getByRole("button", "Add environment", { exact: true }).tap();
    await screen.getByRole("textbox", "Host", { exact: true }).fill(pairing.pairingUrl ?? pairing.url ?? `http://127.0.0.1:41877/pair#token=${pairing.token ?? pairing.credential}`);
    await screen.getByRole("dialog", "Add Environment", { exact: true }).getByRole("button", "Add environment", { exact: true }).tap();
    await screen.getByRole("dialog", "Add Environment", { exact: true }).waitFor({ state: "hidden" });
    await app.open("/");
    await screen.getByText("or start without a project", { exact: true }).tap();
    await screen.getByText("No project", { exact: true }).first().waitFor();
    await new Promise(r => setTimeout(r, 1000));
    const picker = screen.getByRole("combobox", "Run on", { exact: true });
    // Base has only a static machine label; capture that state before asserting the missing control.
    if (await picker.count()) await picker.tap();
    // Replace only synthetic filesystem locations in the diagnostic for public captures.
    await browser.evaluate((root: string) => {
      const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      while (walker.nextNode()) {
        const node = walker.currentNode;
        if (node.textContent?.includes("Threads without a project are off because")) {
          node.textContent = node.textContent.replaceAll(root, "/demo/workspace");
        }
      }
    }, T3_HOME.split("/.t3/")[0]!);
    await new Promise(r => setTimeout(r, 500));
    await app.screenshot("no-project-run-on");
    await expect(picker).toBeVisible();
    await expect(screen.getByText("Threads without a project are off because", { exact: false })).toBeVisible();
    await expect(screen.getByText("Then restart T3 Code.", { exact: false })).toBeVisible();
  } finally {
    child.kill("SIGTERM");
    await once(child, "exit");
  }
});
