"""AC60 method tutorial: restricted hierarchical inference on frozen public GWTC-3 data.

Inputs (committed): 23 O3b BBH candidates with FAR < 1/yr (1500 PE samples each) and 20000 of the
39069 found O3b BBH sensitivity injections. Output: outputs/hierarchical-inference-results.json.

Run:  python hierarchical_mass_inference.py
"""
import json
import platform
import sys

import numpy as np

from frozen_inputs import OUTPUTS, check_input_hashes, load_found_injections, load_manifest, load_posterior_samples, sha256, INPUTS
from hierarchical_likelihood import event_terms, event_weights, injection_weights, marginal_summary, normalized_posterior, selection_terms
from population_model import BETA, HUBBLE_CONSTANT, KAPPA, M_MIN, OMEGA_MATTER, Z_MAX

ALPHA_GRID = np.round(np.arange(0.0, 7.0001, 0.05), 4)
M_MAX_GRID = np.round(np.arange(40.0, 100.0001, 0.5), 4)
MINIMUM_EVENT_EFFECTIVE_SAMPLES = 20


def run_inference(posteriors, injections, total_generated):
    observed = len(posteriors)
    log_event_sum = np.zeros((len(ALPHA_GRID), len(M_MAX_GRID)))
    minimum_event_effective = np.full_like(log_event_sum, np.inf)
    weakest_event = np.empty(log_event_sum.shape, dtype=object)
    per_event = {}
    for name, samples in posteriors.items():
        likelihood, effective = event_terms(event_weights(samples), len(samples), ALPHA_GRID, M_MAX_GRID)
        with np.errstate(divide="ignore"):
            log_event_sum += np.log(likelihood)
        weaker = effective < minimum_event_effective
        weakest_event[weaker] = name
        minimum_event_effective = np.minimum(minimum_event_effective, effective)
        per_event[name] = effective
    fraction, variance, selection_effective = selection_terms(injection_weights(injections), total_generated, ALPHA_GRID, M_MAX_GRID)
    with np.errstate(divide="ignore"):
        log_selection = np.log(fraction)
    return {
        "observed": observed,
        "log_event_sum": log_event_sum,
        "log_selection": log_selection,
        "selection_fraction": fraction,
        "selection_effective": selection_effective,
        "minimum_event_effective": minimum_event_effective,
        "weakest_event": weakest_event,
        "per_event_effective": per_event,
    }


def summarize(terms, include_selection=True, hard_mask=False):
    """Grid posterior. Cells failing the Monte Carlo checks are reported as flagged mass; with
    hard_mask=True they are removed instead (shown only to illustrate why a data-dependent cut misleads)."""
    observed = terms["observed"]
    log_posterior = terms["log_event_sum"] - (observed * terms["log_selection"] if include_selection else 0)
    reliable = terms["minimum_event_effective"] >= MINIMUM_EVENT_EFFECTIVE_SAMPLES
    if include_selection:
        reliable &= terms["selection_effective"] > 4 * observed
    valid = np.isfinite(log_posterior) & (reliable if hard_mask else True)
    posterior = normalized_posterior(log_posterior, valid)
    alpha_marginal = posterior.sum(axis=1)
    m_max_marginal = posterior.sum(axis=0)
    peak = np.unravel_index(np.argmax(posterior), posterior.shape)
    return {
        "posterior": posterior,
        "flaggedMass": float(posterior[~reliable].sum()),
        "alpha": marginal_summary(ALPHA_GRID, alpha_marginal),
        "mMax": marginal_summary(M_MAX_GRID, m_max_marginal),
        "alphaMarginal": alpha_marginal,
        "mMaxMarginal": m_max_marginal,
        "peak": {"alpha": float(ALPHA_GRID[peak[0]]), "mMax": float(M_MAX_GRID[peak[1]])},
        "peakIndex": peak,
    }


def naive_histogram_slope(posteriors, m_max=100.0):
    """Failure case: maximum-likelihood power-law slope fitted to the detected median primary masses."""
    medians = np.array([np.median(samples[:, 0]) for samples in posteriors.values()])
    grid = np.linspace(-3, 7, 2001)
    from population_model import primary_normalization

    log_likelihood = np.array([-a * np.log(medians).sum() - len(medians) * np.log(primary_normalization(a, m_max)) for a in grid])
    return float(grid[np.argmax(log_likelihood)]), medians


def smaller_injection_sets(injections, total_generated, observed, sizes=(2000, 500), m_max=60.0):
    """Failure case: with fewer injections Farr's criterion N_eff > 4 N_obs fails at steep slopes."""
    column = int(np.searchsorted(M_MAX_GRID, m_max))
    report = []
    for size in sizes:
        subset = injections[:size]
        _, _, effective = selection_terms(injection_weights(subset), total_generated * size / len(injections), ALPHA_GRID, M_MAX_GRID)
        failing = ALPHA_GRID[effective[:, column] <= 4 * observed]
        report.append({"foundInjections": size, "mMax": m_max, "firstFailingAlpha": float(failing.min()) if len(failing) else None,
                       "effectiveAtAlpha2p6": float(effective[int(np.searchsorted(ALPHA_GRID, 2.6)), column])})
    return report


def split_half_selection_check(injections, total_generated, points=((1.0, 60.0), (2.6, 60.0), (2.6, 90.0), (4.0, 50.0), (6.0, 80.0))):
    """Independent check: detectable fractions from even- and odd-indexed injections agree within Monte Carlo error."""
    halves = [injections[0::2], injections[1::2]]
    rows = []
    for alpha, m_max in points:
        estimates = []
        for half in halves:
            fraction, variance, _ = selection_terms(injection_weights(half), total_generated * len(half) / len(injections), np.array([alpha]), np.array([m_max]))
            estimates.append((float(fraction[0, 0]), float(np.sqrt(variance[0, 0]))))
        (first, first_error), (second, second_error) = estimates
        rows.append({"alpha": alpha, "mMax": m_max, "evenHalf": first, "oddHalf": second,
                     "differenceInSigma": abs(first - second) / float(np.hypot(first_error, second_error))})
    return rows


def rounded(values, digits=5):
    return [float(f"{value:.{digits}g}") for value in np.asarray(values).ravel()]


def main():
    manifest = load_manifest()
    problems = check_input_hashes(manifest)
    if problems:
        sys.exit("\n".join(problems))
    posteriors = load_posterior_samples()
    injections = load_found_injections()
    total_generated = manifest["injections"]["effectiveTotalGenerated"]
    terms = run_inference(posteriors, injections, total_generated)
    corrected = summarize(terms)
    uncorrected = summarize(terms, include_selection=False)
    hard_masked = summarize(terms, hard_mask=True)
    naive_slope, medians = naive_histogram_slope(posteriors)

    peak = corrected["peakIndex"]
    observed = terms["observed"]
    farr_threshold = 4 * observed
    selection_effective = terms["selection_effective"]
    smallest = np.unravel_index(np.argmin(selection_effective), selection_effective.shape)
    subset_failures = smaller_injection_sets(injections, total_generated, observed)
    halves = split_half_selection_check(injections, total_generated)
    low_cut = M_MAX_GRID[terms["minimum_event_effective"][peak[0]] < MINIMUM_EVENT_EFFECTIVE_SAMPLES]
    heavy_samples_above_100 = {name: float(np.mean(samples[:, 0] > 100)) for name, samples in posteriors.items() if np.mean(samples[:, 0] > 100) > 0}

    result = {
        "description": "Restricted hierarchical inference of the BBH primary-mass slope alpha and sharp maximum mass m_max from frozen GWTC-3 O3b data.",
        "software": {"python": platform.python_version(), "numpy": np.__version__},
        "inputs": {
            "posteriorSamplesSha256": sha256(INPUTS / "o3b-bbh-posterior-samples.csv"),
            "foundInjectionsSha256": sha256(INPUTS / "o3b-bbh-found-injections.csv"),
            "events": list(posteriors.keys()),
            "samplesPerEvent": int(len(next(iter(posteriors.values())))),
            "foundInjectionsUsed": int(len(injections)),
            "effectiveTotalGenerated": total_generated,
        },
        "model": {
            "minimumMass": M_MIN, "pairingIndexBeta": BETA, "redshiftIndexKappa": KAPPA, "maximumRedshift": Z_MAX,
            "cosmology": {"H0": HUBBLE_CONSTANT, "OmegaMatter": OMEGA_MATTER, "flat": True},
            "priors": {"alpha": [float(ALPHA_GRID[0]), float(ALPHA_GRID[-1])], "mMax": [float(M_MAX_GRID[0]), float(M_MAX_GRID[-1])], "shape": "uniform on the grid"},
            "units": {"mass": "solar masses (source frame)", "redshift": "dimensionless"},
        },
        "grid": {"alpha": rounded(ALPHA_GRID), "mMax": rounded(M_MAX_GRID)},
        "corrected": {
            "alpha": corrected["alpha"], "mMax": corrected["mMax"], "peak": corrected["peak"],
            "alphaMarginal": rounded(corrected["alphaMarginal"], 4), "mMaxMarginal": rounded(corrected["mMaxMarginal"], 4),
            "selectionEffectiveAtPeak": float(terms["selection_effective"][peak]),
            "detectableFractionAtPeak": float(terms["selection_fraction"][peak]),
            "minimumEventEffectiveAtPeak": float(terms["minimum_event_effective"][peak]),
            "weakestEventAtPeak": str(terms["weakest_event"][peak]),
            "farrThreshold": farr_threshold,
            "posteriorMassInFlaggedCells": corrected["flaggedMass"],
        },
        "withoutSelectionCorrection": {"alpha": uncorrected["alpha"], "mMax": uncorrected["mMax"], "peak": uncorrected["peak"],
                                       "alphaMarginal": rounded(uncorrected["alphaMarginal"], 4)},
        "withHardEffectiveSampleCut": {"alpha": hard_masked["alpha"], "mMax": hard_masked["mMax"], "note": "cells failing the checks removed; not the reported result"},
        "failureCases": {
            "naiveHistogramSlope": {"alpha": naive_slope, "note": "power law fitted to detected median primary masses with m_max = 100, ignoring selection and measurement errors"},
            "selectionMonteCarlo": {
                "farrThreshold": farr_threshold,
                "smallestEffectiveOnGrid": float(selection_effective[smallest]),
                "smallestAt": {"alpha": float(ALPHA_GRID[smallest[0]]), "mMax": float(M_MAX_GRID[smallest[1]])},
                "smallerInjectionSets": subset_failures,
            },
            "independentSelectionHalves": halves,
            "mMaxBelowEventSupport": {"mMaxValuesFlaggedAtPeakAlpha": [float(low_cut.min()), float(low_cut.max())] if len(low_cut) else [],
                                      "minimumEventEffectiveSamples": MINIMUM_EVENT_EFFECTIVE_SAMPLES,
                                      "weakestEventJustBelowLowerBound": str(terms["weakest_event"][peak[0], max(0, int(np.searchsorted(M_MAX_GRID, corrected["mMax"]["lower90"])) - 4)])},
            "posteriorSupportBeyondInjections": {"shareOfSamplesAbove100": heavy_samples_above_100, "note": "injections stop at m1 = 100, so the model cannot place mass there"},
        },
        "perEventEffectiveAtPeak": {name: float(values[peak]) for name, values in terms["per_event_effective"].items()},
        "detectedMedianPrimaryMasses": rounded(medians, 4),
    }
    OUTPUTS.mkdir(exist_ok=True)
    (OUTPUTS / "hierarchical-inference-results.json").write_text(json.dumps(result, indent=2) + "\n")
    print(json.dumps({key: result[key] for key in ["corrected", "withoutSelectionCorrection", "failureCases"]}, indent=1, default=str)[:4000])


if __name__ == "__main__":
    main()
