import { execFileSync } from "node:child_process";
import { writeFileSync, chmodSync, mkdtempSync } from "node:fs";
import { join } from "node:path";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

test("A healthy 37-second remote-base fetch creates the worktree from the fresh commit", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("slow-fetch-demo", { "README.md": "Initial stale checkout\n" });
  const fixture = mkdtempSync("/tmp/factory-pr-24604-a1794641426-evidence-1/remote-");
  const remote = join(fixture, "remote.git");
  git(project, "clone", "--bare", project, remote);
  git(project, "remote", "add", "origin", remote);
  git(project, "fetch", "origin");
  git(project, "branch", "--set-upstream-to=origin/main", "main");
  const stale = git(project, "rev-parse", "HEAD");
  const writer = join(fixture, "writer");
  git(project, "clone", remote, writer);
  const transport = join(fixture, "slow-upload-pack");
  writeFileSync(transport, '#!/bin/sh\nsleep 37\nexec git-upload-pack "$@"\n');
  chmodSync(transport, 0o755);
  git(project, "config", "remote.origin.uploadpack", transport);
  await t3.open();
  // Only anonymize the generated fixture path in displayed errors, including video frames.
  await browser.evaluate((fixturePath: string) => {
    const fixtureRoot = fixturePath.slice(0, fixturePath.indexOf("/.t3/"));
    const redact = () => {
      const nodes = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
      let node: Node | null;
      while ((node = nodes.nextNode())) {
        if (node.textContent?.includes(fixtureRoot)) node.textContent = node.textContent.replaceAll(fixturePath, "/synthetic/slow-fetch-demo").replaceAll(fixtureRoot, "/synthetic");
      }
    };
    new MutationObserver(redact).observe(document.body, { subtree: true, childList: true, characterData: true });
    redact();
  }, project);
  await screen.getByRole("combobox", "Workspace", { exact: true }).tap();
  await screen.getByRole("option", "New worktree").tap();
  // Let the initial background fetch settle before advancing the remote.
  await wait(40_000);
  await browser.locator('[aria-label^="Branch:"]:visible').first().tap();
  const remoteSwitch = screen.getByRole("switch", "Start worktree from remote");
  if (!(await remoteSwitch.isChecked())) await remoteSwitch.tap();
  await browser.keyboard.press("Escape");
  await app.screenshot("remote-worktree-selected");
  writeFileSync(join(writer, "fresh-remote.txt"), "Fresh commit fetched through the slow transport\n");
  git(writer, "add", ".");
  git(writer, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Fresh remote commit");
  git(writer, "push", "origin", "main");
  const fresh = git(writer, "rev-parse", "HEAD");
  git(project, "update-ref", "refs/remotes/origin/main", stale);
  await screen.getByRole("textbox").fill("Show me the fresh remote commit");
  await screen.getByRole("textbox").press("Enter");
  await wait(38_000);
  const dismissError = screen.getByRole("button", "Dismiss error", { exact: true });
  if (await dismissError.count()) await dismissError.tap();
  await app.screenshot("fetch-at-38-seconds");
  await wait(10_000);
  await app.screenshot("slow-fetch-outcome");
  const worktrees = git(project, "worktree", "list", "--porcelain");
  const created = worktrees.split("\n\n").map(block => block.split("\n")[0]?.replace("worktree ", "")).find(path => path && path !== project);
  expect(created ? git(created, "rev-parse", "HEAD") : "no worktree created").toBe(fresh);
});
