import json
import os


def fmt(x):
    if x is None:
        return "--"
    if isinstance(x, bool):
        return "true" if x else "false"
    return str(x)


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", "row25_stress", "result.json")
    out_path = os.path.join("results", "row25_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{{\\RowXXVVerdict}}{{{tex_escape(data.get('verdict', '--'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXVRunTag}}{{{tex_escape(data.get('gate', '--'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXVTier}}{{{tex_escape(data.get('tier', '--'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXVContext}}{{{tex_escape(data.get('context', '--'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXVNTests}}{{{fmt(data.get('n_tests'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXVNPass}}{{{fmt(data.get('n_pass'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXVNPending}}{{{fmt(data.get('n_pending'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXVNFail}}{{{fmt(data.get('n_fail'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXVCriticalTriggered}}{{{fmt(data.get('critical_triggered'))}}}\n")
    out.append(f"\\newcommand{{\\RowXXVNotes}}{{{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()