import { execFileSync } from "node:child_process";

const repoPath = process.env.REPO_PATH || "";
const repository = process.env.REPOSITORY || "";
const sourceBranch = process.env.SOURCE_BRANCH || "";
const snapshotPrefix = (process.env.SNAPSHOT_PREFIX || "").replace(/\/+$/u, "");
const gitopsBranch = process.env.GITOPS_BRANCH || "";

function rev(ref) {
  if (!ref) return null;
  try {
    const out = execFileSync("git", [`--git-dir=${repoPath}`, "rev-parse", "--verify", `${ref}^{commit}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
    return /^[0-9a-f]{40}$/iu.test(out) ? out : null;
  } catch {
    return null;
  }
}

const localSource = rev(`refs/heads/${sourceBranch}`);
const githubSource = rev(`refs/mirror-stage/heads/${sourceBranch}`);
const snapshotSource = githubSource || localSource;
const sourceStageRef = snapshotSource ? `${snapshotPrefix}/${snapshotSource}` : null;
const sourceSnapshot = sourceStageRef === null ? null : rev(sourceStageRef);
const localGitops = gitopsBranch ? rev(`refs/heads/${gitopsBranch}`) : null;
const githubGitops = gitopsBranch ? rev(`refs/mirror-stage/heads/${gitopsBranch}`) : null;
const pendingFlush = gitopsBranch ? Boolean(localGitops && localGitops !== githubGitops) : null;
const githubInSync = gitopsBranch ? Boolean(!localGitops || localGitops === githubGitops) : null;
const sourceSnapshotReady = snapshotSource ? sourceSnapshot === snapshotSource : false;

process.stdout.write(JSON.stringify({
  ok: Boolean(localSource) && sourceSnapshotReady && pendingFlush !== true,
  repository,
  repoPath,
  sourceBranch,
  gitopsBranch: gitopsBranch || null,
  localSource,
  githubSource,
  sourceStageRef,
  sourceSnapshot,
  sourceSnapshotReady,
  localGitops,
  githubGitops,
  pendingFlush,
  githubInSync,
  statusAuthority: "k8s-git-mirror-cache",
  valuesRedacted: true,
}));
