"""Rerun every AC69 tutorial number and compare it with expected-outputs.json.

Usage:  python3 reproduce.py            # compare against expected-outputs.json
        python3 reproduce.py --write    # overwrite expected-outputs.json
Requires Python >= 3.10, numpy and scipy. A full run takes a few seconds.
"""
import hashlib
import json
import math
import platform
import sys
from pathlib import Path

import numpy as np
import scipy

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE / "scripts"))

import cluster_count_selection  # noqa: E402
from cluster_mass_function import ClusterMassFunction, FlatLambdaCdm  # noqa: E402
from compare_catalogues import compare_catalogues  # noqa: E402
from xcop_hydrostatic_masses import analyse_cluster, load  # noqa: E402

CLUSTERS = ("a2029", "a2319")
CATALOGUE_INPUT = "inputs/observed-catalogues.json"
# Fits and integrals are deterministic but may move slightly between scipy versions.
RELATIVE_TOLERANCE = 1e-3
MONTE_CARLO_TOLERANCE = 0.02
CHECKED_CLUSTER_KEYS = (
    "radius500Kiloparsec", "mass500", "gasFraction500", "constantAlphaEstimate",
    "sphericalCompton500Mpc2", "mass500FromUniversalGasFraction", "mass500FromPlanckYMRelation",
)


def input_checksums():
    paths = [*(f"inputs/xcop-{name}.json" for name in CLUSTERS), CATALOGUE_INPUT]
    return {path: hashlib.sha256((HERE / path).read_bytes()).hexdigest() for path in paths}


def mass_function_table():
    cosmology = FlatLambdaCdm()
    rows = []
    for sigma8 in (0.7, 0.81, 0.9):
        function = ClusterMassFunction(cosmology, sigma8, 0.2)
        for mass in (2e14, 4e14, 1e15):
            rows.append({"sigma8": sigma8, "mass500": mass, "cumulativeDensityPerMpc3": function.cumulative(mass)})
    return rows


def relative_change(got, want):
    return abs(got - want) / max(abs(want), 1e-300)


def compare(outputs, expected):
    worst = {"cluster": 0.0, "massFunction": 0.0, "expectedCounts": 0.0, "degeneracy": 0.0, "monteCarlo": 0.0}
    for got, want in zip(outputs["xcop"], expected["xcop"]):
        for key in CHECKED_CLUSTER_KEYS:
            worst["cluster"] = max(worst["cluster"], relative_change(got[key], want[key]))
    worst["catalogues"] = 0.0
    for got, want in zip(outputs["observedCatalogueComparison"], expected["observedCatalogueComparison"], strict=True):
        if got.keys() != want.keys() or got["cluster"] != want["cluster"]:
            raise ValueError("Frozen catalogue outputs changed structure")
        for key in got:
            if key != "cluster":
                worst["catalogues"] = max(worst["catalogues"], relative_change(got[key], want[key]))
    for got, want in zip(outputs["massFunction"], expected["massFunction"]):
        worst["massFunction"] = max(worst["massFunction"], relative_change(got["cumulativeDensityPerMpc3"], want["cumulativeDensityPerMpc3"]))
    survey, reference = outputs["survey"], expected["survey"]
    for got, want in zip(survey["expectedCountsPerRedshiftBin"], reference["expectedCountsPerRedshiftBin"]):
        worst["expectedCounts"] = max(worst["expectedCounts"], relative_change(got, want))
    for got, want in zip(survey["degeneracy"], reference["degeneracy"]):
        worst["degeneracy"] = max(worst["degeneracy"], relative_change(got["sigma8FromExpectedTotal"], want["sigma8FromExpectedTotal"]))
    worst["monteCarlo"] = relative_change(survey["monteCarloMeanTotal"], reference["monteCarloMeanTotal"])
    passed = all(value <= RELATIVE_TOLERANCE for key, value in worst.items() if key != "monteCarlo") and worst["monteCarlo"] <= MONTE_CARLO_TOLERANCE
    return worst, passed


def main():
    cluster_records = [load(HERE / "inputs" / f"xcop-{name}.json") for name in CLUSTERS]
    outputs = {
        "environment": {"python": platform.python_version(), "numpy": np.__version__, "scipy": scipy.__version__},
        "inputChecksums": input_checksums(),
        "xcop": [analyse_cluster(record) for record in cluster_records],
        "observedCatalogueComparison": compare_catalogues(load(HERE / CATALOGUE_INPUT), cluster_records),
        "massFunction": mass_function_table(),
        "survey": cluster_count_selection.run(),
    }
    if "--write" in sys.argv:
        (HERE / "expected-outputs.json").write_text(json.dumps(outputs, indent=2) + "\n", encoding="utf-8")
        print("wrote expected-outputs.json")
        return
    expected = json.loads((HERE / "expected-outputs.json").read_text(encoding="utf-8"))
    if outputs["inputChecksums"] != expected["inputChecksums"]:
        print("input files differ from the frozen copies")
        sys.exit(1)
    worst, passed = compare(outputs, expected)
    print(json.dumps({"largestRelativeChange": worst, "pass": passed}, indent=2))
    for row in outputs["xcop"]:
        print(f"{row['cluster']}: M500 HSE {row['mass500']:.3e} (published {row['publishedMass500']:.3e}), "
              f"f_gas {row['gasFraction500']:.3f}, M500 from f_gas {row['mass500FromUniversalGasFraction']:.3e}, "
              f"M500 from Planck Y-M {row['mass500FromPlanckYMRelation']:.3e}")
    for row in outputs["observedCatalogueComparison"]:
        print(f"{row['cluster']}: Planck catalogue proxy {row['planckProxyMass500']:.3f}, "
              f"hydrostatic mass after Planck core cut {row['cutMass500']:.3f}, in 10^14 solar masses")
        if "matchedXcopToLensingRatio" in row:
            print(f"  common {row['matchedApertureMpc']:.2f} Mpc aperture: "
                  f"published hydrostatic to weak-lensing mass ratio {row['matchedXcopToLensingRatio']:.3f}")
    survey = outputs["survey"]
    print(f"toy survey: {survey['expectedTotal']:.1f} expected detections, Monte Carlo mean {survey['monteCarloMeanTotal']:.1f}")
    for row in survey["degeneracy"]:
        print(f"  assume 1-b = {row['assumedOneMinusBias']:.1f} -> sigma8 = {row['sigma8FromExpectedTotal']:.4f}")
    sys.exit(0 if passed and math.isfinite(survey["expectedTotal"]) else 1)


if __name__ == "__main__":
    main()
