#!/usr/bin/env python3
"""Phase 1: run compare.py for every in-scope book (no letters).

Sequential; each book writes reports/{key}_comparison.html + {key}_diffs.json.
Logs a one-line result per book (total_diffs if parseable, else status).
"""
import subprocess, re, os, time

BASE = os.path.dirname(os.path.abspath(__file__))
KEYS = ("bg iso noi poy pop lob ekc rvidya bbd owk pqpa kcty ttp tlc tlk tqk nod "
        "ssr ejop krp kb cc_adi1 cc_adi2 cc_adi3 sb31 sb11 sb12 sb13 sb21 sb22 "
        "sb32 sb33 sb34 sb41 sb42 sb43 sb44 sb51 sb52 sb61 sb62 sb63 sb71 sb72 "
        "sb73 sb81 sb82 sb83 sb91 sb92 sb93 sb101 sb102 sb103 cc_mad1 cc_mad2 "
        "cc_mad3 cc_mad4 cc_mad5 cc_mad6 cc_mad7 cc_mad8 cc_mad9 cc_ant1 cc_ant2 "
        "cc_ant3 cc_ant4 cc_ant5").split()

def main():
    t0 = time.time()
    ok = fail = 0
    for i, k in enumerate(KEYS, 1):
        st = time.time()
        r = subprocess.run(["python3", os.path.join(BASE, "compare.py"), k],
                           capture_output=True, text=True, cwd=BASE)
        out = r.stdout + r.stderr
        m = re.search(r"total_diffs:\s*(\d+)", out)
        if r.returncode == 0 and m:
            ok += 1
            print(f"[{i}/{len(KEYS)}] {k:10s} total_diffs={m.group(1):>6}  ({time.time()-st:.0f}s)", flush=True)
        else:
            fail += 1
            tail = out.strip().splitlines()[-1][:160] if out.strip() else "no output"
            print(f"[{i}/{len(KEYS)}] {k:10s} FAIL rc={r.returncode}  {tail}", flush=True)
    print(f"=== DONE  ok={ok} fail={fail}  total {time.time()-t0:.0f}s ===", flush=True)

if __name__ == "__main__":
    main()
