import json
import os


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


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", "row22_nz", "result.json")
    out_path = os.path.join("results", "row22_results.tex")

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

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

    verdict = data.get("verdict", "PENDING_DATA")
    run_tag = data.get("gate", "neutral_zone_sandwich")
    rule = data.get("rule", "--")

    eps_m = metrics.get("eps_m")
    rho_max = metrics.get("rho_max")
    smin_L = metrics.get("smin_L")
    smin_U = metrics.get("smin_U")

    out = []
    out.append("% Auto-generated. DO NOT EDIT BY HAND.\n")
    out.append(f"\\newcommand{{\\RowXXIIVerdict}}{{{tex_escape(verdict)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIIRunTag}}{{{tex_escape(run_tag)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIIRule}}{{{tex_escape(rule)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIIEpsM}}{{{fmt(eps_m)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIIRhoMax}}{{{fmt(rho_max)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIISminL}}{{{fmt(smin_L)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIISminU}}{{{fmt(smin_U)}}}\n")

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

    print(f"Wrote {out_path}")


if __name__ == "__main__":
    main()