import { execFileSync } from "node:child_process";
import { writeFileSync, chmodSync, readFileSync, existsSync, mkdtempSync } from "node:fs";
import { join, relative } from "node:path";
import { setTimeout } from "node:timers/promises";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("A completed push stays successful when the final status finds an index lock", WEB, async ({ t3, app, screen }) => {
  const runDir = mkdtempSync("/tmp/factory-pr-32705-a1794722146-evidence-1/push-");
  const titlePath = join("..", relative(join(T3_HOME, "workspaces"), join(runDir, "sample")));
  const sample = await t3.project(titlePath, { "README.md": "Initial README\n" });
  execFileSync(process.execPath, ["apps/server/src/bin.ts", "project", "rename", sample, "push-status-demo", "--base-dir", T3_HOME], { cwd: APP_DIR });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: sample, encoding: "utf8" }).trim();
  const remote = `${sample}/../remote.git`;
  git("config", "user.name", "Scenario");
  git("config", "user.email", "scenario@example.invalid");
  git("init", "--bare", remote);
  git("remote", "add", "origin", remote);
  git("push", "-u", "origin", "main");
  git("checkout", "-b", "feature/readme-update");
  writeFileSync(`${sample}/README.md`, "Updated README\n");
  git("add", "README.md");
  git("commit", "-m", "Update README");
  const thread = await t3.thread({ project: sample, title: "Push README update", messages: ["Ready for push"] });
  const hook = `${remote}/hooks/post-receive`;
  writeFileSync(hook, `#!/bin/bash\nfor name in $(env | sed -n 's/^\\(GIT_[^=]*\\)=.*/\\1/p'); do unset "$name"; done\nGIT_EDITOR='sleep 90; true' setsid git -C '${sample}' commit -a --allow-empty </dev/null >/dev/null 2>&1 &\necho $! > '${remote}/holder.pid'\nfor i in $(seq 1 500); do [ -f '${sample}/.git/index.lock' ] && exit 0; sleep 0.02; done\nexit 1\n`);
  chmodSync(hook, 0o755);
  try {
    await t3.open(thread);
    await screen.getByRole("button", "Git action options").tap();
    await screen.getByRole("menuitem", "Push", { exact: true }).tap();
    await screen.getByText(/Action failed|Pushed to origin/).first().waitFor({ state: "visible", timeout: 60000 });
    const remoteHead = git("ls-remote", "origin", "refs/heads/feature/readme-update").split(/\s/)[0];
    if (remoteHead !== git("rev-parse", "HEAD") || !existsSync(`${sample}/.git/index.lock`)) {
      throw new Error("Fixture did not land the push while holding the index lock");
    }
    await setTimeout(500);
    await app.screenshot("settled-result");
    await setTimeout(500);
    await app.screenshot("push-result");
    await expect(screen.getByText("Pushed to origin/feature/readme-update", { exact: false })).toBeVisible();
  } finally {
    if (existsSync(`${remote}/holder.pid`)) {
      const pid = Number(readFileSync(`${remote}/holder.pid`, "utf8").trim());
      try { process.kill(-pid, "SIGTERM"); } catch {}
    }
  }
});
