/// <reference lib="dom" />
import { expect } from "e2e";
import { mkdtemp, writeFile, readFile, chmod } from "node:fs/promises";
import { setTimeout } from "node:timers/promises";
import { test, WEB, runPromise } from "./t3.ts";
import { run } from "./shell.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Commit only with zero fetch interval never contacts origin", WEB, async ({t3, app, screen, browser}) => {
  const scratch = await mkdtemp(`${process.env.T3_PROOF_SCRATCH}/run-`);
  const project = await t3.project("fetch-demo", {"README.md": "Initial content\n"});
  const git = (...args: string[]) => runPromise(run("git", args, {cwd: project}));
  await git("config", "user.name", "Scenario");
  await git("config", "user.email", "scenario@example.invalid");
  await git("init", "--bare", `${scratch}/origin.git`);
  await git("remote", "add", "origin", `${scratch}/origin.git`);
  await git("push", "-u", "origin", "main");
  const log = `${scratch}/ssh.log`;
  const ssh = `${scratch}/ssh`;
  await writeFile(log, "");
  await writeFile(ssh, `#!/bin/sh\nprintf 'ssh-connect git-upload-pack origin\\n' >> '${log}'\nshift\nexec sh -c "$*"\n`);
  await chmod(ssh, 0o755);
  await git("remote", "set-url", "origin", `ssh://fakehost${scratch}/origin.git`);
  await git("config", "core.sshCommand", ssh);
  await git("config", "ssh.variant", "ssh");
  const thread = await t3.thread({project, title:"Commit without automatic fetch", messages:["first"]});
  await t3.open(thread);
  const environment = await browser.evaluate(async () => (await (await fetch('/.well-known/t3/environment')).json()).environmentId);
  await t3.open(`/settings/maintenance?machine=${environment}`);
  await screen.getByRole("combobox", "Background activity profile").tap({timeout:120000});
  await screen.getByRole("option", "Advanced").tap();
  await screen.getByRole("textbox", "Git fetch interval in seconds").fill("0");
  await browser.keyboard.press("Tab");
  await screen.getByRole("button", "Done", {exact:true}).tap();
  await writeFile(`${project}/README.md`, "Initial content\nLocal edit\n");
  await setTimeout(17000);
  await t3.open(thread);
  await screen.getByRole("button", "Git action options").tap({timeout:120000});
  await screen.getByRole("menuitem", "Commit", {exact:true}).tap();
  await screen.getByPlaceholder("Leave empty to auto-generate").fill("Edit README");
  await setTimeout(17000);
  await writeFile(log, "");
  await app.screenshot("before-commit");
  await screen.getByRole("button", "Commit", {exact:true}).tap();
  for (let i=0;i<100;i++) {
    if ((await git("log", "-1", "--format=%s")).stdout.trim() === "Edit README") break;
    await setTimeout(200);
  }
  await setTimeout(2500);
  const connections = (await readFile(log, "utf8")).trim();
  const commit = (await git("log", "-1", "--format=%s")).stdout.trim();
  const ahead = (await git("rev-list", "--count", "origin/main..HEAD")).stdout.trim();
  const saved = JSON.parse(await readFile(`${T3_HOME}/userdata/settings.json`, "utf8"));
  const interval = saved.automaticGitFetchInterval;
  if (interval !== 0 || commit !== "Edit README" || ahead !== "1") throw new Error("Reproduction setup or commit did not complete");
  await browser.evaluate(({connections, commit, ahead, interval}) => {
    const panel = document.createElement('div');
    panel.style.cssText='position:fixed;bottom:24px;left:24px;z-index:99999;background:#111827;color:white;padding:20px;border:2px solid #94a3b8;border-radius:8px;font:16px monospace;white-space:pre;max-width:740px';
    panel.textContent=`External SSH monitor (scenario instrumentation)\nPersisted Git fetch interval: ${interval} seconds\nAction: Commit only | Commit: ${commit}\nAhead of cached origin/main: ${ahead}\nSSH connections during commit: ${connections ? connections.split('\\n').length : 0}\n${connections || 'No connection to origin'}`;
    document.body.append(panel);
  }, {connections, commit, ahead, interval});
  await app.screenshot("commit-fetch-result");
  await expect(connections).toBe("");
});
