import { execFile } from "node:child_process";
import { promisify } from "node:util";

const execFileAsync = promisify(execFile);

async function git (repoRoot, args)
{
	const { stdout } = await execFileAsync("git", args, {
		cwd: repoRoot,
		windowsHide: true,
		maxBuffer: 1024 * 1024
	});
	return String(stdout ?? "").trim();
}

/**
 * Non-destructive check: fetch origin and see if remote branch is ahead of HEAD.
 * @returns {Promise<{ ok: true, ahead: boolean, local: string, remote: string }
 *   | { ok: false, error: string }>}
 */
export async function checkGitRemoteAhead (repoRoot, branch = "master")
{
	try
	{
		const local = await git(repoRoot, ["rev-parse", "HEAD"]);
		await git(repoRoot, ["fetch", "--quiet", "origin", branch]);
		const remote = await git(repoRoot, ["rev-parse", `origin/${branch}`]);
		if (!local || !remote)
		{ return { ok: false, error: "Missing git commit hashes." }; }
		if (local === remote)
		{ return { ok: true, ahead: false, local, remote }; }
		const counts = await git(repoRoot, ["rev-list", "--left-right", "--count", `HEAD...origin/${branch}`]);
		// "A\tB" = commits reachable from HEAD not remote, commits from remote not HEAD
		const parts = counts.split(/\s+/);
		const behind = Number(parts[1]) || 0;
		return { ok: true, ahead: behind > 0, local, remote };
	}
	catch (error)
	{
		return { ok: false, error: error?.message ?? String(error) };
	}
}
