import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const fixture = JSON.parse(readFileSync(process.env.SSH_FIXTURE_JSON!, "utf8"));

test("An unattended SSH key approval gives an actionable worktree error", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("SSH approval demo");
  const git = (...args: string[]) => execFileSync("git", ["-C", project, ...args]);
  git("remote", "add", "origin", fixture.local);
  git("fetch", "origin");
  git("remote", "set-url", "origin", fixture.remote);
  try {
  await t3.open();
  await screen.getByRole("button", /Run context:|Current checkout/).tap();
  await screen.getByRole("menuitemradio", "New worktree").tap();
  await screen.getByRole("textbox").fill("say hello");
  await screen.getByRole("textbox").press("Enter");
  // Both versions eventually fail; the user needs the reason and an action to take.
  await screen.getByText("Worktree setup failed").waitFor({ timeout: 60_000 });
  await screen.getByRole("button", "Dismiss error").tap();
  await app.screenshot("ssh-authorization-result");
  await expect(screen.getByText("Git is waiting for SSH key authorization.", { exact: false }).first()).toBeVisible();
  } finally {
    const children = readFileSync(`/proc/${fixture.agentPid}/task/${fixture.agentPid}/children`, "utf8").trim().split(/\s+/).filter(Boolean);
    for (const pid of children) process.kill(Number(pid), "SIGTERM");
  }
});
