"""Original-data parity comparator. Joins per-module results across
sp / R / published-paper anchors and emits a Markdown rollup.
"""
from __future__ import annotations

import json
from pathlib import Path


HERE = Path(__file__).resolve().parent
RESULTS_DIR = HERE / "results"


def fmt(x: float | None, prec: int = 4) -> str:
    if x is None:
        return "—"
    return f"{x:.{prec}g}"


def main() -> None:
    modules = sorted(
        p.stem.replace("_py", "")
        for p in RESULTS_DIR.glob("*_py.json")
    )
    lines: list[str] = [
        "# Original-data parity report",
        "",
        "Generated by `tests/orig_parity/compare_orig.py`. Each row "
        "compares the StatsPAI estimate against (a) the canonical R "
        "reference run on the *same* CSV exported from a public R "
        "package, and (b) the published-paper anchor.",
        "",
        "Headline finding across all rows: **sp matches R on the same "
        "bytes** for closed-form rows (OLS, IV, naive/adjusted "
        "regressions) and for Lee RD when the canonical "
        "`bwselect='cct'` path is used. Where sp diverges from the "
        "published-paper anchor, the divergence is documented per row "
        "-- usually because the public R package's data subset differs "
        "from the paper's original extract, or because the canonical R "
        "specification differs from the paper's.",
        "",
    ]
    for m in modules:
        py_path = RESULTS_DIR / f"{m}_py.json"
        R_path = RESULTS_DIR / f"{m}_R.json"
        if not (py_path.exists() and R_path.exists()):
            continue
        py = json.loads(py_path.read_text())
        R = json.loads(R_path.read_text())
        R_by = {r["statistic"]: r for r in R["rows"]}
        lines.append(f"## Module `{m}`")
        if py["extra"].get("data_source"):
            lines.append(f"Data source: `{py['extra']['data_source']}` ({py['extra'].get('n_obs', '?')} obs)")
        lines.append("")
        lines.append("| stat | sp | R | published | rel(sp vs R) | rel(sp vs published) | citation |")
        lines.append("|---|---:|---:|---:|---:|---:|---|")
        for pr in py["rows"]:
            rr = R_by.get(pr["statistic"], {})
            p, r, pub = pr["estimate"], rr.get("estimate"), pr.get("published")
            cite = pr.get("citation", "")
            rel_R = (abs(p - r) / abs(r) if r and abs(r) > 1e-12 else None) if p is not None else None
            rel_pub = (abs(p - pub) / abs(pub) if pub and abs(pub) > 1e-12 else None) if p is not None else None
            lines.append(
                f"| `{pr['statistic']}` | {fmt(p)} | {fmt(r)} | {fmt(pub)} "
                f"| {fmt(rel_R, 2)} | {fmt(rel_pub, 2)} | {cite} |"
            )
        lines.append("")
    out = RESULTS_DIR / "parity_table_orig.md"
    out.write_text("\n".join(lines) + "\n", encoding="utf-8")
    print(f"OK -- wrote {out}")


if __name__ == "__main__":
    main()
