#!/usr/bin/env python3
"""
Genera el reporte de diferencias repo vs escaneo (la verdad).

Lee out/<book>.adjudicated.jsonl si existe (con veredicto Llama), si no
out/<book>.candidates.jsonl. Produce:
  out/report.html   (agrupado por libro, diffs reales arriba)
  out/report.tsv    (book, page, repo, original, veredicto, nota)

Uso: python3 report.py
"""
import json, html, sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
CFG = json.loads((HERE / "books.json").read_text())
OUT = HERE / "out"

def load(book):
    adj = OUT / f"{book}.adjudicated.jsonl"
    cand = OUT / f"{book}.candidates.jsonl"
    f = adj if adj.exists() else cand
    if not f.exists():
        return None, []
    return ("adjudicated" if f == adj else "candidates"), [json.loads(l) for l in f.open()]

def is_real(c):
    m = c.get("llm")
    return isinstance(m, dict) and m.get("is_real_diff") is True

def main():
    rows_tsv = []
    sections = []
    tot_real = tot_pend = 0
    for book in CFG["books"]:
        kind, items = load(book)
        if not items:
            continue
        reals = [c for c in items if is_real(c)]
        # pendientes = adjudicados no-reales se omiten; si solo hay candidates, mostrar REVISAR/REPO_TYPO
        if kind == "adjudicated":
            pend = []
        else:
            pend = [c for c in items if c["verdict"] in ("REVISAR", "REPO_TYPO", "AMBIGUO")]
        tot_real += len(reals); tot_pend += len(pend)
        if not reals and not pend:
            continue
        h = [f"<h2>{html.escape(book)} "
             f"<small>({'adjudicado' if kind=='adjudicated' else 'sin adjudicar'} · "
             f"{len(reals)} reales{', '+str(len(pend))+' pendientes' if pend else ''})</small></h2>"]
        def table(title, cs, cls):
            if not cs: return ""
            r = [f"<h3>{title}</h3>",
                 f"<table class='{cls}'><tr><th>pág</th><th>repo</th><th>→ original (escaneo)</th><th>conf</th><th>nota</th></tr>"]
            for c in cs:
                m = c.get("llm", {}) if isinstance(c.get("llm"), dict) else {}
                orig = m.get("original_reading") or c.get("scan", "")
                pg = c.get("page", "").split("#")[-1]
                r.append("<tr>"
                         f"<td>{html.escape(pg)}</td>"
                         f"<td class='repo'>{html.escape(c['repo'])}</td>"
                         f"<td class='scan'>{html.escape(orig)}</td>"
                         f"<td>{html.escape(str(m.get('confidence','')))}</td>"
                         f"<td>{html.escape(str(m.get('note','')))}</td></tr>")
                rows_tsv.append("\t".join([book, pg, c['repo'], orig,
                                           "REAL" if is_real(c) else c['verdict'],
                                           str(m.get('note',''))]))
            r.append("</table>")
            return "\n".join(r)
        h.append(table("Diferencias confirmadas (la repo difiere del original)", reals, "real"))
        h.append(table("Pendientes de adjudicar", pend, "pend"))
        sections.append("\n".join(h))

    doc = f"""<!doctype html><meta charset=utf-8>
<title>Diff repo vs escaneos originales</title>
<style>
body{{font:14px/1.5 -apple-system,sans-serif;margin:2rem;max-width:1100px}}
h1{{margin-bottom:0}} h2{{margin-top:2rem;border-bottom:2px solid #333}}
small{{font-weight:normal;color:#666}}
table{{border-collapse:collapse;width:100%;margin:.5rem 0}}
td,th{{border:1px solid #ccc;padding:4px 8px;vertical-align:top;text-align:left}}
.repo{{background:#fff0f0}} .scan{{background:#f0fff0}}
table.real th{{background:#fee}} table.pend th{{background:#eef}}
</style>
<h1>Repo vedabase-original vs escaneos (1ª edición = verdad)</h1>
<p>Diferencias reales confirmadas: <b>{tot_real}</b> · pendientes: <b>{tot_pend}</b></p>
{''.join(sections)}
"""
    (OUT / "report.html").write_text(doc)
    (OUT / "report.tsv").write_text("book\tpag\trepo\toriginal\tveredicto\tnota\n" +
                                    "\n".join(rows_tsv) + "\n")
    print(f"report.html y report.tsv escritos. reales={tot_real} pendientes={tot_pend}",
          file=sys.stderr)

if __name__ == "__main__":
    main()
