"""Run the full tutorial: fits, failure cases and degeneracy scan.

Usage:
  python3 reproduce.py          recompute and compare with expected-outputs.json (exit 0 on pass)
  python3 reproduce.py --write  recompute and overwrite expected-outputs.json
A full run takes about three minutes on a laptop.
"""
import hashlib
import json
import math
import os
import platform
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import fit_jets  # noqa: E402

SLICE = os.path.join(HERE, "gw170817-frozen-slice.json")
EXPECTED = os.path.join(HERE, "expected-outputs.json")


def differences(saved, fresh, path=""):
    """Yield (path, saved, fresh, excess) for every leaf that differs beyond its tolerance."""
    if isinstance(saved, dict):
        for key in saved:
            if key != "python":
                yield from differences(saved[key], fresh.get(key) if isinstance(fresh, dict) else None, path + "/" + key)
    elif isinstance(saved, list):
        if not isinstance(fresh, list) or len(fresh) != len(saved):
            yield path, saved, fresh, math.inf
            return
        for index, (a, b) in enumerate(zip(saved, fresh)):
            yield from differences(a, b, path + "/" + str(index))
    elif isinstance(saved, bool) or isinstance(saved, str):
        if saved != fresh:
            yield path, saved, fresh, math.inf
    elif isinstance(saved, (int, float)):
        if not isinstance(fresh, (int, float)):
            yield path, saved, fresh, math.inf
            return
        tolerance = max(0.01, 0.002 * abs(saved))
        if abs(fresh - saved) > tolerance:
            yield path, saved, fresh, abs(fresh - saved) - tolerance


def summarize(kind, params, value, rows):
    detections = sum(1 for row in rows if not row["upper_limit"])
    radio = [row for row in rows if row["band"] == "radio-3GHz"]
    limits = [row for row in rows if row["upper_limit"]]
    limit_fluxes = fit_jets.model_fluxes(kind, params, limits)
    return {
        "viewing_angle_deg": round(params[0], 3),
        "core_angle_deg": round(params[1], 3),
        "log10_core_energy_erg": round(params[2], 3),
        "log10_density_cm3": round(params[3], 3),
        "viewing_to_core_ratio": round(params[0] / params[1], 3),
        "chi_square": round(value, 2),
        "detections": detections,
        "chi_square_per_point": round(value / detections, 3),
        "radio_rise_slope_15_60d": round(fit_jets.log_slope(kind, params, 3e9, 15, 60), 3),
        "radio_decline_slope_300_800d": round(fit_jets.log_slope(kind, params, 3e9, 300, 800), 3),
        "radio_detections": sum(not row["upper_limit"] for row in radio),
        "radio_upper_limits": sum(row["upper_limit"] for row in radio),
        "upper_limits_respected": all(flux <= row["flux_ujy"] for row, flux in zip(limits, limit_fluxes)),
    }


def main():
    rows = fit_jets.load_slice(SLICE)
    outputs = {"fixed_parameters": fit_jets.FIXED, "bounds": fit_jets.BOUNDS}
    gaussian, gaussian_value = fit_jets.fit("gaussian", rows, [22.0, 3.8, 52.6, -2.5])
    outputs["gaussian_fit"] = summarize("gaussian", gaussian, gaussian_value, rows)
    top_hat, top_hat_value = fit_jets.fit("top-hat", rows, [22.0, 3.8, 52.6, -2.5])
    outputs["top_hat_fit"] = summarize("top-hat", top_hat, top_hat_value, rows)
    scan = []
    for viewing in (15.0, 20.0, 25.0, 30.0, 35.0):
        start = [viewing, viewing / gaussian[0] * gaussian[1], gaussian[2], gaussian[3]]
        params, value = fit_jets.fit("gaussian", rows, start, fixed_viewing=viewing)
        scan.append(summarize("gaussian", params, value, rows))
    outputs["gaussian_viewing_angle_scan"] = scan
    with open(SLICE, "rb") as handle:
        outputs["input_sha256"] = hashlib.sha256(handle.read()).hexdigest()
    outputs["python"] = platform.python_version()
    outputs = json.loads(json.dumps(outputs))
    print(json.dumps(outputs, indent=1))
    if "--write" in sys.argv[1:]:
        with open(EXPECTED, "w") as handle:
            json.dump(outputs, handle, indent=1)
        print("wrote", EXPECTED)
        return 0
    with open(EXPECTED) as handle:
        saved = json.load(handle)
    failures = list(differences(saved, outputs))
    for path, old, new, _ in failures:
        print("DIFFERS", path, "saved", old, "now", new)
    print("PASS" if not failures else "FAIL", "-", len(failures), "values outside tolerance (max(0.01, 0.2 percent))")
    return 0 if not failures else 1


if __name__ == "__main__":
    sys.exit(main())
