#!/usr/bin/env node
// review-ok: a pull request merges only with a review that actually happened.
//
// Passes on exactly one of:
//   1. an APPROVED GitHub review of the head commit, by a human login that is not the PR author;
//   2. a review of record at .reviews/PR-<n>.json, read out of the HEAD commit (never the checkout),
//      naming a reviewer distinct from the author, verdict "merge", a written note, and a
//      reviewed_sha whose code equals the head's (only the record file may differ).
//
// Never passes on: bot comments of any kind (a "usage limit" notice is not a review), bot
// approvals, the author's own approval, an approval of an older commit, or a missing record.
// Fails closed: anything it cannot read is a failure, not "nothing to gate".
//
// Runs under pull_request_target with the BASE branch checked out, so a pull request cannot
// edit this script or the workflow to pass itself. The head is only read as data (git show),
// never executed.

import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";

const fail = (code, msg) => {
  console.log(`review-ok: FAIL [${code}] ${msg}`);
  process.exit(1);
};
const pass = (msg) => {
  console.log(`review-ok: PASS ${msg}`);
  process.exit(0);
};
const git = (...args) =>
  execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();

const SHA = /^[0-9a-f]{40}$/;
const MIN_NOTE = 40;

let event;
try {
  event = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8"));
} catch {
  fail("CONTEXT_UNREADABLE", "cannot read the event payload");
}
const pr = event.pull_request;
if (!pr) fail("CONTEXT_UNREADABLE", `event ${process.env.GITHUB_EVENT_NAME} carries no pull request`);

const n = pr.number;
const head = pr.head?.sha;
const author = (pr.user?.login || "").toLowerCase();
const repo = process.env.GITHUB_REPOSITORY;
if (!SHA.test(head || "") || !author || !repo) fail("CONTEXT_UNREADABLE", "pull request fields missing");

// --- Path 1: a real approval of the head commit -------------------------------------------
const token = process.env.GITHUB_TOKEN;
if (!token) fail("CONTEXT_UNREADABLE", "GITHUB_TOKEN not set");
let reviews;
try {
  const res = await fetch(`${process.env.GITHUB_API_URL || "https://api.github.com"}/repos/${repo}/pulls/${n}/reviews?per_page=100`, {
    headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json" },
  });
  if (!res.ok) throw new Error(String(res.status));
  reviews = await res.json();
} catch (e) {
  fail("CONTEXT_UNREADABLE", `cannot list reviews (${e.message})`);
}
const approval = reviews.find(
  (r) =>
    r.state === "APPROVED" &&
    r.commit_id === head &&
    r.user &&
    r.user.type !== "Bot" &&
    !/\[bot\]$/i.test(r.user.login) &&
    r.user.login.toLowerCase() !== author,
);
if (approval) pass(`approved by @${approval.user.login} at ${head.slice(0, 7)}`);

// --- Path 2: a review of record in the head commit ----------------------------------------
const recordPath = `.reviews/PR-${n}.json`;
try {
  git("fetch", "--no-tags", "--quiet", "origin", head);
} catch {
  // The head may already be present; a missing object surfaces below as unreadable.
}
let raw;
try {
  raw = git("show", `${head}:${recordPath}`);
} catch {
  fail(
    "NO_REVIEW",
    `no approving review of ${head.slice(0, 7)} and no ${recordPath} in the head commit. ` +
      `Bot comments, including usage-limit notices, never count.`,
  );
}
let rec;
try {
  rec = JSON.parse(raw);
} catch {
  fail("BAD_RECORD", `${recordPath} is not valid JSON`);
}

if (rec.pr !== n) fail("BAD_RECORD", `record names PR ${rec.pr}, this is PR ${n}`);
if (rec.verdict !== "merge")
  fail("HOLD", `reviewer verdict is "${rec.verdict}" — a hold goes to Alex`);
const reviewer = String(rec.reviewer || "").trim();
const recAuthor = String(rec.author || "").trim();
if (!reviewer || !recAuthor) fail("BAD_RECORD", "record needs both author and reviewer");
if (reviewer.toLowerCase() === recAuthor.toLowerCase())
  fail("SELF_REVIEW", "reviewer and author are the same — the writing session cannot review its own branch");
if (/codex|usage limit/i.test(reviewer))
  fail("BAD_RECORD", "reviewer names the Codex connector, which is not a reviewer here");
if (String(rec.note || "").trim().length < MIN_NOTE)
  fail("BAD_RECORD", `note must say what was read and found (at least ${MIN_NOTE} characters)`);
const at = Date.parse(rec.reviewed_at);
if (Number.isNaN(at)) fail("BAD_RECORD", "reviewed_at is not a timestamp");
if (at > Date.now() + 5 * 60 * 1000) fail("BAD_RECORD", "reviewed_at is in the future");
if (!SHA.test(String(rec.reviewed_sha || ""))) fail("BAD_RECORD", "reviewed_sha must be a full 40-character sha");

// The reviewed commit must be the head or an ancestor whose code equals the head's.
try {
  git("merge-base", "--is-ancestor", rec.reviewed_sha, head);
} catch {
  fail("STALE_REVIEW", `reviewed ${rec.reviewed_sha.slice(0, 7)} is not an ancestor of head ${head.slice(0, 7)}`);
}
let changed;
try {
  changed = git("-c", "core.quotePath=false", "diff", "--no-renames", "--name-only", rec.reviewed_sha, head)
    .split("\n")
    .filter(Boolean);
} catch {
  fail("CONTEXT_UNREADABLE", "cannot diff the reviewed commit against head");
}
const extra = changed.filter((p) => p !== recordPath);
if (extra.length)
  fail("STALE_REVIEW", `code changed after the review: ${extra.slice(0, 5).join(", ")}${extra.length > 5 ? " …" : ""}`);

pass(`review of record by ${reviewer} at ${rec.reviewed_sha.slice(0, 7)} (head ${head.slice(0, 7)})`);
