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

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

    out = []
    out.append("% Auto-generated. DO NOT EDIT BY HAND.\n")
    out.append(f"\\newcommand{{\\RowXXIVVerdict}}{{{tex_escape(data.get('verdict', '--'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXIVRunTag}}{{{tex_escape(data.get('gate', '--'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXIVTier}}{{{tex_escape(data.get('tier', '--'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXIVContext}}{{{tex_escape(data.get('context', '--'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXIVNModels}}{{{fmt(data.get('n_models'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXIVMeanAucGain}}{{{fmt(data.get('mean_auc_gain'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXIVMinAucGain}}{{{fmt(data.get('min_auc_gain'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXIVViolations}}{{{fmt(data.get('total_violations'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXIVNotes}}{{{tex_escape(data.get('notes', '--'))}}}\n")

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

    print(f"Wrote {out_path}")


if __name__ == "__main__":
    main()