#!/usr/bin/env bash
# CHECK — git worktree census re-derivation verification.
#
# Re-derives the census from live `git` (current checkout) and compares it,
# field-for-field, against the committed git-worktree-census-2026-10-30.json.
# Exits 0 only on exact match.
set -u

REPO=/root/troupe-standup
OUT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
JSON="$OUT/git-worktree-census-2026-10-30.json"

python3 - "$JSON" <<'PY'
import json, subprocess, sys
from collections import Counter

json_path = sys.argv[1]
repo = "/root/troupe-standup"

def git(*args):
    return subprocess.run(["git", "-C", repo, *args],
                          capture_output=True, text=True, check=True).stdout

def derive():
    data = {}
    data["commit_count"] = int(git("rev-list", "--count", "HEAD").strip())
    data["tracked_file_count"] = len(git("ls-files").splitlines())
    data["total_unique_emails"] = len(set(e for e in git("log", "--format=%ae").splitlines() if e))
    data["ahead_by_origin_main"] = int(git("rev-list", "--count", "origin/main..HEAD").strip())
    data["behind_by_origin_main"] = int(git("rev-list", "--count", "HEAD..origin/main").strip())
    data["branch_head"] = git("rev-parse", "--short", "HEAD").strip()
    data["branch"] = git("rev-parse", "--abbrev-ref", "HEAD").strip()
    data["remote_heads"] = {
        l: git("rev-parse", "--short", l).strip()
        for l in git("branch", "-r", "--format=%(refname:short)").splitlines() if l.strip()
    }
    by_pair = {}
    for line in git("log", "--format=%an%x00%ae%x00%ad", "--date=iso-strict").splitlines():
        if not line.strip():
            continue
        name, email, date = line.split("\x00")
        by_pair.setdefault((name, email), []).append(date)
    rows = []
    for (name, email), dates in by_pair.items():
        rows.append({"name": name, "email": email, "count": len(dates),
                     "first": min(dates), "last": max(dates)})
    nc = Counter(r["name"] for r in rows)
    ec = Counter(r["email"] for r in rows)
    for r in rows:
        r["name_collides"] = nc[r["name"]] > 1
        r["email_collides"] = ec[r["email"]] > 1
    rows.sort(key=lambda r: (-r["count"], r["name"].lower(), r["email"]))
    data["author_census"] = rows
    names = git("log", "--pretty=format:", "--name-only").splitlines()
    fc = Counter(n for n in names if n.strip())
    data["top_modified_files"] = [{"path": p, "commits": c} for p, c in fc.most_common(60)]
    return data

derived = derive()
committed = json.load(open(json_path))
fields = ["commit_count", "tracked_file_count", "total_unique_emails",
          "ahead_by_origin_main", "behind_by_origin_main", "branch_head",
          "branch", "remote_heads"]
for k in fields:
    if derived.get(k) != committed.get(k):
        print("  FIELD %r MISMATCH: derived=%r committed=%r" %
              (k, derived.get(k), committed.get(k)), file=sys.stderr)
        sys.exit(1)
if len(derived["author_census"]) != len(committed["author_census"]):
    print("  CENSUS LENGTH MISMATCH: derived %d rows, committed %d rows" %
          (len(derived["author_census"]), len(committed["author_census"])), file=sys.stderr)
    sys.exit(1)
for i, (e, c) in enumerate(zip(derived["author_census"], committed["author_census"])):
    for k in ("name", "email", "count", "first", "last", "name_collides", "email_collides"):
        if e.get(k) != c.get(k):
            print("  CENSUS ROW %d FIELD %r MISMATCH: derived=%r committed=%r" %
                  (i, k, e.get(k), c.get(k)), file=sys.stderr)
            sys.exit(1)
if derived["top_modified_files"] != committed["top_modified_files"]:
    print("  TOP_FILES MISMATCH", file=sys.stderr)
    sys.exit(1)
print("[CHECK] derived from live git and compared field-for-field against %s — PASS" % json_path)
PY
