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

const fixture = "/tmp/factory-issue-45720-evidence-1";
const log = `${fixture}/pinentry.log`;
const readLog = () => { try { return readFileSync(log, "utf8"); } catch { return ""; } };

test("idle background Git fetch does not ask gpg-agent to store an SSH key", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("SSH background status", { "README.md": "Real OpenSSH and gpg-agent idle-fetch reproduction.\n" });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, env: { ...process.env, SSH_AUTH_SOCK: "" } });
  git("config", "core.sshCommand", `ssh -F ${fixture}/ssh_config`);
  git("remote", "add", "origin", `evidence-git:${fixture}/remote.git`);
  git("push", "--force", "--set-upstream", "origin", "main");
  await t3.open();
  await screen.getByRole("button", "New thread in SSH background status", { exact: true }).tap();
  writeFileSync(log, "");
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const input = screen.getByRole("textbox", "Terminal input");
  await expect(input).toHaveAttribute("data-workspace-focus-default", "");
  await input.focus();
  await browser.keyboard.type(`PS1='evidence> '; clear; printf 'Real gpg-agent pinentry log -- idle default 30s background fetch\\n'; tail -n +1 -f ${log}\n`);
  const sshBefore = readFileSync(`${fixture}/sshd.log`, "utf8").split("Accepted publickey").length;
  // The defect repeats on the real default 30-second background refresh interval.
  await setTimeout(70_000);
  const accepted = readFileSync(`${fixture}/sshd.log`, "utf8").split("Accepted publickey").length - sshBefore;
  const transcript = readLog();
  const prompts = transcript.split("PINENTRY START").length - 1;
  writeFileSync(`${project}/evidence.txt`, [
    "REAL SSH / GPG-AGENT BACKGROUND FETCH", "Linux; OpenSSH; GnuPG 2.4.4; default 30s poll",
    "IdentityFile + IdentitiesOnly yes + AddKeysToAgent yes",
    "No messages or Git actions during 70 seconds idle.",
    `Successful SSH authentications during idle: ${accepted}`,
    `Pinentry starts during idle: ${prompts}`,
    `Prompt times: ${transcript.split("\n").filter(line => line.includes("PINENTRY START")).join(", ") || "none"}`,
    transcript.split("\n").find(line => line.startsWith("SETDESC"))?.replaceAll("%0A", "\n") || "No pinentry requests.",
  ].join("\n"));
  await input.focus();
  await browser.keyboard.press("Control+c");
  await browser.keyboard.type("PS1='evidence> '; clear; cat evidence.txt\n");
  await setTimeout(1500);
  await app.screenshot("idle-background-fetch-pinentry");
  if (accepted < 2) throw new Error("Background fetch did not run twice during idle");
  expect(prompts).toBe(0);
});
