#!/usr/bin/env python3
"""ledger_append.py — one calibration row in research/_calibration/ledger.md, only after blind_check passes.
Usage: ledger_append.py --target T --run RUN --confirmed N --refuted N --stale N --unverifiable N [--high-refuted N --high-total N] [--override-reason "..."]"""
import datetime, os, subprocess, sys
def a(n, d="0"):
    return sys.argv[sys.argv.index(n) + 1] if n in sys.argv else d
here = os.path.dirname(os.path.abspath(__file__))
blind = subprocess.run([sys.executable, os.path.join(here, "blind_check.py")]).returncode == 0
if not blind:
    print("refused: blind_check.py failed"); sys.exit(1)
c, r, s, u = (int(a(k)) for k in ("--confirmed", "--refuted", "--stale", "--unverifiable"))
tot = c + r
rate = f"{round(100 * r / tot)}%" if tot else "—"
hr, ht = int(a("--high-refuted")), int(a("--high-total"))
path = os.path.join("research", "_calibration", "ledger.md")
os.makedirs(os.path.dirname(path), exist_ok=True)
if not os.path.exists(path):
    open(path, "w").write("# Calibration ledger\n\n| Date | Target | Run | Confirmed | Refuted | Stale | Unverifiable | Refuted rate | High band refuted | Blind | Override |\n| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n")
row = f"| {datetime.date.today()} | {a('--target')} | {a('--run')} | {c} | {r} | {s} | {u} | {rate} | {hr}/{ht} | computed | {a('--override-reason', '—')} |\n"
open(path, "a").write(row)
print(row.strip())
