import json
from pathlib import Path

IN_JSON = Path("results/row19_results.json")
OUT_TEX = Path("results/row19_results.tex")

def fmt(x):
    if x is None:
        return "--"
    if isinstance(x, bool):
        return "true" if x else "false"
    if isinstance(x, float):
        return f"{x:.6g}"
    if isinstance(x, (list, tuple)):
        return "[" + ", ".join(fmt(v) for v in x) + "]"
    return str(x)

def main():
    data = json.loads(IN_JSON.read_text(encoding="utf-8"))

    frg = data.get("frg", {}) or {}
    pos = data.get("positivity", {}) or {}
    pg  = data.get("ppn_gw", {}) or {}
    jac = data.get("jacobian", {}) or {}
    scan = data.get("scan_summary", {}) or {}

    out = []
    out.append("% Auto-generated. DO NOT EDIT BY HAND.\n")
    out.append("\\newcommand{\\RowXIXVerdict}{" + fmt(data.get("verdict","PENDING")) + "}\n")
    out.append("\\newcommand{\\RowXIXNscan}{" + fmt(scan.get("n_points")) + "}\n")

    out.append("\\newcommand{\\RowXIXFPfound}{" + fmt(frg.get("fixed_point_found")) + "}\n")
    out.append("\\newcommand{\\RowXIXgstar}{" + fmt(frg.get("gstar")) + "}\n")
    out.append("\\newcommand{\\RowXIXlstar}{" + fmt(frg.get("lambdastar")) + "}\n")
    out.append("\\newcommand{\\RowXIXthetas}{" + fmt(frg.get("critical_exponents")) + "}\n")

    out.append("\\newcommand{\\RowXIXPosNonEmpty}{" + fmt(pos.get("region_nonempty")) + "}\n")
    out.append("\\newcommand{\\RowXIXPosMargin}{" + fmt(pos.get("min_margin")) + "}\n")

    out.append("\\newcommand{\\RowXIXPPNok}{" + fmt(pg.get("ppn_ok")) + "}\n")
    out.append("\\newcommand{\\RowXIXGWok}{" + fmt(pg.get("gw_speed_ok")) + "}\n")

    out.append("\\newcommand{\\RowXIXJacOK}{" + fmt(jac.get("analytic_numeric_agree")) + "}\n")
    out.append("\\newcommand{\\RowXIXJacErr}{" + fmt(jac.get("max_rel_err")) + "}\n")

    OUT_TEX.parent.mkdir(parents=True, exist_ok=True)
    OUT_TEX.write_text("".join(out), encoding="utf-8")
    print(f"Wrote {OUT_TEX}")

if __name__ == "__main__":
    main()