import json
import os


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

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

    verdict = data.get("verdict", "PENDING_DATA")
    run_tag = data.get("gate", "bh_ringdown_echoes")
    tier = data.get("tier", "--")
    context = data.get("context", "--")
    notes = data.get("notes", "--")

    out = []
    out.append("% Auto-generated. DO NOT EDIT BY HAND.\n")
    out.append(f"\\newcommand{{\\RowXXIIIVerdict}}{{{tex_escape(verdict)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIIIRunTag}}{{{tex_escape(run_tag)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIIITier}}{{{tex_escape(tier)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIIIContext}}{{{tex_escape(context)}}}\n")
    out.append(f"\\newcommand{{\\RowXXIIINotes}}{{{tex_escape(notes)}}}\n")

    n_events = data.get("n_events")
    max_freq_frac_err = data.get("max_freq_frac_err")
    max_tau_frac_err = data.get("max_tau_frac_err")

    out.append(f"\\newcommand{{\\RowXXIIINEvents}}{{{n_events if n_events is not None else '--'}}}\n")
    out.append(f"\\newcommand{{\\RowXXIIIMaxFreqErr}}{{{max_freq_frac_err if max_freq_frac_err is not None else '--'}}}\n")
    out.append(f"\\newcommand{{\\RowXXIIIMaxTauErr}}{{{max_tau_frac_err if max_tau_frac_err is not None else '--'}}}\n")

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

    print(f"Wrote {out_path}")


if __name__ == "__main__":
    main()