"""Convert the raw PARI output (data/bsd_raw_r4.txt) into
data/bsd_curves_r4.json with run metadata and human-readable
Weierstrass equations. Same reformatting as compute/bsd_curves_r2.py;
the numbers come only from the PARI run.
"""
import hashlib
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent
DATA = HERE.parent / "data"


def human_eq(coeffs):
    a1, a2, a3, a4, a6 = coeffs
    lhs = "y^2"
    if a1:
        lhs += f" + {a1}xy" if a1 != 1 else " + xy"
    if a3:
        lhs += f" + {a3}y" if a3 != 1 else " + y"
    rhs = "x^3"
    if a2:
        rhs += f" + {a2}x^2" if a2 > 0 else f" - {-a2}x^2"
    if a4:
        rhs += f" + {a4}x" if a4 > 0 else f" - {-a4}x"
    if a6:
        rhs += f" + {a6}" if a6 > 0 else f" - {-a6}"
    return f"{lhs} = {rhs}"


def main():
    raw = json.loads((DATA / "bsd_raw_r4.txt").read_text())
    curves = []
    for c in raw["curves"]:
        coeffs = json.loads(c["equation"])
        curves.append({
            "label": c["label"],
            "equation": c["equation"],
            "weierstrass": human_eq(coeffs),
            "conductor": c["conductor"],
            "rank": c["rank"],
            "rank_method": "PARI ellanalyticrank: analytic rank, order of vanishing of L(E,s) at s=1",
            "L_value": c["L_value"],
            "L_value_at": "s=1",
            "L_method": "PARI ellanalyticrank, realprecision 30",
            "torsion_order": c["torsion"],
            "source": "PARI/GP 2.19.1, elldata (Cremona database), enumerated with ellsearch for conductors 1-40; conductor recomputed here with ellglobalred",
        })
    runtime_file = DATA / "bsd_r4_seconds.txt"
    runtime = float(runtime_file.read_text().strip()) if runtime_file.exists() else None
    out = {
        "run": "bsd-curve-family-r4",
        "date": "2026-11-20",
        "family": "every elliptic curve over Q of conductor at most 40, as enumerated by PARI ellsearch",
        "method": "PARI/GP 2.19.1 ellanalyticrank at realprecision 30; conductor recomputed with ellglobalred per curve",
        "curves_count": len(curves),
        "ranks": sorted({c["rank"] for c in curves}),
        "all_L_nonzero": all(float(c["L_value"]) != 0.0 for c in curves),
        "runtime_seconds": runtime,
        "curves": curves,
    }
    p = DATA / "bsd_curves_r4.json"
    p.write_text(json.dumps(out, indent=2))
    from collections import Counter
    print(f"curves: {len(curves)}, rank split: {dict(Counter(c['rank'] for c in curves))}")
    print(f"results_sha256: {hashlib.sha256(p.read_bytes()).hexdigest()}")
    print(f"results_file: {p}")


if __name__ == "__main__":
    main()
