import json
import os


def fmt(x, digits=6):
    if x is None:
        return "--"
    try:
        v = float(x)
    except Exception:
        return str(x)
    s = f"{v:.{digits}g}"
    return s


def tex_escape(s: str) -> str:
    return (
        str(s)
        .replace("\\", r"\textbackslash{}")
        .replace("_", r"\_")
        .replace("%", r"\%")
        .replace("&", r"\&")
        .replace("#", r"\#")
        .replace("{", r"\{")
        .replace("}", r"\}")
    )


def main():
    in_path = os.path.join("results", "row21_axion", "result.json")
    out_path = os.path.join("results", "row21_results.tex")

    with open(in_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    summary = data.get("summary", {}) or {}

    verdict = data.get("verdict", "PENDING_DATA")
    run_tag = data.get("signature", "ROW21_AXION_GATE_v1")

    m_min = summary.get("m_min_ueV", data.get("m_min_ueV"))
    m_max = summary.get("m_max_ueV", data.get("m_max_ueV"))
    frac_allowed = summary.get("frac_allowed_known", data.get("frac_allowed_known"))
    max_ratio = summary.get("max_pred_over_limit", data.get("max_pred_over_limit"))

    out = []
    out.append("% Auto-generated. DO NOT EDIT BY HAND.\n")
    out.append(f"\\newcommand{{\\RowXXIVerdict}}{{{tex_escape(verdict)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIRunTag}}{{{tex_escape(run_tag)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIMmin}}{{{fmt(m_min)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIMmax}}{{{fmt(m_max)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIFracAllowed}}{{{fmt(frac_allowed)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIMaxPredOverLimit}}{{{fmt(max_ratio)}}}\n")

    with open(out_path, "w", encoding="utf-8") as f:
        f.writelines(out)

    print(f"Wrote {out_path}")


if __name__ == "__main__":
    main()