#!/usr/bin/env python3
# Evidence-law gate for the check-in census. Exits 0 only if the table is
# derivable from the real files + real git objects. Nothing may be phantom.
import csv
import os
import re
import subprocess
import sys

ROOT = "/root/troupe-standup"
os.chdir(ROOT)

def git(*a):
    return subprocess.run(
        ["git", "-C", ROOT] + list(a), check=True, capture_output=True, text=True
    ).stdout

# Expected table, derived FROM GIT (not from the CSV).
files = sorted(f for f in git("ls-files", "checkins/").strip().split("\n") if f.endswith(".md"))
dated = [f for f in files if re.match(r"^checkins/\d{4}-\d{2}-\d{2}-", f) and not f.endswith("README.md")]
indexed = [f for f in files if f.endswith("README.md")]
print("tracked md files on git: %d | dated checkin files: %d | index file: %d" % (len(files), len(dated), len(indexed)))

rows = list(csv.DictReader(open("wizard-work/ledger/2026-10-29-checkin-census/checkin-census.csv")))
print("table rows present: %d" % len(rows))

fails = []
# 1) Row count must equal source files (index row = README.md).
if len(rows) != len(dated) + len(indexed):
    fails.append("table rows != dated files + index file")

# 2) No dated file may be missing from the table, and nothing un-tracked may appear.
disk_files = set(r["file"] for r in rows)
ghost = sorted(f for f in dated if f not in disk_files)
if ghost:
    fails.append("dated files missing from table: %s" % ghost)
notracked = sorted(f for f in disk_files if f not in set(files))
if notracked:
    fails.append("table rows not tracked by git: %s" % notracked)

# 3) Every data row carries a real committer (a git object must exist for the file).
empty_commits = sorted(r["file"] for r in rows if not r["committer"] or r["committer"] == "(no committer)")
if empty_commits:
    fails.append("rows with empty/none committer: %s" % empty_commits)

# 4) Per-signee disk counts must reconcile with the table (no lost files).
disk_counts = {}
for f in dated:
    m = re.match(r"^checkins/(\d{4}-\d{2}-\d{2}-(.+?))(?:-\d+)?\.md$", f)
    if m:
        s = re.sub(r"-\d+$", "", m.group(2))
        disk_counts[s] = disk_counts.get(s, 0) + 1
table_counts = {}
for r in rows:
    if r["file"] == "checkins/README.md":
        continue
    table_counts[r["signee"]] = table_counts.get(r["signee"], 0) + 1
mismatch = [(s, disk_counts.get(s, 0), table_counts.get(s, 0)) for s in sorted(set(disk_counts) | set(table_counts)) if disk_counts.get(s, 0) != table_counts.get(s, 0)]
if mismatch:
    fails.append("signee counts mismatch disk vs table: %s" % mismatch)

if fails:
    print("CHECK: FAILED")
    for x in fails:
        print("  -", x)
    sys.exit(1)

print("CHECK: PASSED")
print("VERDICT: 0 (correct)")
