#!/usr/bin/env python3
"""Re-run the comparison using master.pdf (the 2258p EN final master) as the
vedabase side, with per-book page ranges auto-derived in master_ranges.json.
Reports go to reports_master/ (old reports/ untouched).

Skips: bg (verse_by_chapter uses hardcoded 14k chapter detection), and any book
not anchored in the master (iso, ttp).
"""
import compare as c, json, os, time

c.VEDABASE_PDF = c.BASE_DIR / "master.pdf"
c.OUTPUT_DIR = c.BASE_DIR / "reports_master"
c.OUTPUT_DIR.mkdir(exist_ok=True)

mr = json.load(open(c.BASE_DIR / "master_ranges.json"))
for k, r in mr.items():
    if k in c.BOOKS:
        c.BOOKS[k]["vedabase_start"] = r["vedabase_start"]
        c.BOOKS[k]["vedabase_end"] = r["vedabase_end"]

SKIP = {"bg"}  # verse_by_chapter: needs page-range support, not wired for master
keys = [k for k in mr if k not in SKIP]
print(f"Re-diff contra master.pdf: {len(keys)} libros", flush=True)
t0 = time.time(); ok = fail = 0
for i, k in enumerate(keys, 1):
    st = time.time()
    try:
        import io, contextlib
        buf = io.StringIO()
        with contextlib.redirect_stdout(buf):
            c.compare_book(k)
        # read back the diff count
        j = json.load(open(c.OUTPUT_DIR / f"{k}_diffs.json"))
        td = j["stats"]["total_diffs"]
        ok += 1
        print(f"[{i}/{len(keys)}] {k:9s} total_diffs={td:>6}  ({time.time()-st:.0f}s)", flush=True)
    except Exception as e:
        fail += 1
        print(f"[{i}/{len(keys)}] {k:9s} FAIL {str(e)[:80]}", flush=True)
print(f"=== DONE ok={ok} fail={fail}  {time.time()-t0:.0f}s ===", flush=True)
