import { expect } from "e2e";
import { execFileSync, spawnSync } from "node:child_process";
import { writeFileSync, readFileSync, existsSync, unlinkSync } from "node:fs";
import { test, WEB } from "./t3.ts";
import { APP_DIR } from "../e2e.config.ts";
const scratch = "/tmp/factory-pr-19764-evidence-3";
const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim();
test("Unanswered SSH approval reports how to authorize the key, preserving the fetch deadline", WEB, async ({ t3, app, screen, browser }) => {
  writeFileSync(`${scratch}/remote-mode`, "normal");
  if (existsSync(`${scratch}/approve`)) unlinkSync(`${scratch}/approve`);
  await browser.setViewport({ width: 1600, height: 1100 });
  const stableCapture = async (label: string) => {
    await browser.mouse.move(1400, 800);
    await browser.mouse.down();
    await browser.mouse.up();
    await browser.mouse.move(1, 700);
    let previous = await app.screenshot(`${label}-settle-0`);
    for (let i = 1; i <= 12; i++) {
      await browser.evaluate(() => new Promise((resolve) => setTimeout(resolve, 500)));
      const next = await app.screenshot(`${label}-settle-${i}`);
      if (spawnSync("compare", ["-metric", "AE", previous, next, "null:"]).status === 0) {
        console.log(`Stable capture ${label}: ${next}`);
        return next;
      }
      previous = next;
    }
    throw new Error(`Capture never became pixel-identical: ${label}`);
  };
  const project = await t3.project("SSH approval", { "README.md": "Synthetic SSH approval proof\n" });
  git(project, "clone", "--bare", project, `${project}-remote.git`);
  git(project, "remote", "add", "origin", `approval-proof:${project}-remote.git`);
  git(project, "update-ref", "refs/remotes/origin/main", "HEAD");
  git(project, "config", "branch.main.remote", "origin");
  git(project, "config", "branch.main.merge", "refs/heads/main");
  const revision = git(APP_DIR, "rev-parse", "HEAD");
  writeFileSync(`${scratch}/seed-${revision}.json`, JSON.stringify({
    revision,
    initialCommit: git(project, "rev-parse", "HEAD"),
    originMain: git(project, "rev-parse", "origin/main"),
    upstream: git(project, "rev-parse", "--abbrev-ref", "@{upstream}"),
    files: git(project, "ls-files").split("\n"),
    gitSshConfig: spawnSync("git", ["config", "--get-regexp", "^(core\\.sshcommand|ssh\\.variant|submodule\\..*\\.url)$"], { cwd: project, encoding: "utf8" }).stdout,
    gitmodulesExists: existsSync(`${project}/.gitmodules`),
    approvalInitiallyPending: !existsSync(`${scratch}/approve`),
  }, null, 2));
  await t3.open();
  await screen.getByRole("combobox", "Workspace").tap();
  await screen.getByRole("option", "New worktree").tap();
  await screen.getByRole("textbox").fill("Give me a short tour");
  await screen.getByText("From main (remote)", { exact: true }).first().waitFor();
  await stableCapture("same-repository-before-fetch");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("Worktree setup failed", { exact: true }).waitFor({ state: "visible", timeout: 60000 });
  const notification = screen.getByRole("button", "Dismiss notification");
  if (await notification.count()) await notification.first().tap();
  const dismissError = screen.getByRole("button", "Dismiss error");
  if (await dismissError.count()) await dismissError.tap();
  await stableCapture("pending-approval-error");
  const failure = await browser.evaluate(() => document.body.innerText);
  writeFileSync(`${scratch}/approve`, "approve each pending signature");
  await screen.getByRole("button", "Retry", { exact: true }).tap();
  await screen.getByText("This turn is a replay.", { exact: false }).waitFor({ timeout: 60000 });
  await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden", timeout: 60000 });
  await stableCapture("approved-retry-agent-finished");
  expect(failure).toContain("SSH key authorization timed out.");
});
