"""Recompute a simplified GW170817 bright-siren H0 posterior from the public GWTC-1 distance samples.

Data: LIGO-Virgo GWTC-1 posterior samples for GW170817 (DCC LIGO-P1800370-v5), sky position fixed to the optical
counterpart. The file is downloaded, checked against a SHA-256 digest and never redistributed by this tutorial.
Method (Abbott et al. 2017, Nature 551, 85, Eqs. 4-9, simplified): the samples were drawn with a distance prior
proportional to d^2, the same prior the paper adopts, so the d-integral is a sample mean of N(v_H; H0 d, sigma_v).
The Hubble-flow velocity is taken as one Gaussian, v_H = 3017 +- 166 km/s, instead of the paper's separate
recession and peculiar-velocity terms. The detection normalisation is constant for a distance prior (paper text).
Run: python3 recompute_gw170817_bright_siren.py GW170817_GWTC-1.hdf5 gw170817-bright-siren-outputs.json
"""
import hashlib
import json
import platform
import sys
import urllib.request
from pathlib import Path

import h5py
import numpy as np
import scipy

SOURCE_URL = "https://dcc.ligo.org/public/0157/P1800370/005/GW170817_GWTC-1.hdf5"
SOURCE_SHA256 = "eff59472991bb0f0fa8c1e58057093ce07b82eb4c112364e3578ba16fe54eca9"
HUBBLE_FLOW_VELOCITY, HUBBLE_FLOW_SIGMA = 3017.0, 166.0
GRID = np.linspace(20.0, 160.0, 2801)


def fetch(path):
    if not path.exists():
        request = urllib.request.Request(SOURCE_URL, headers={"User-Agent": "sandboxphysics-tutorial/1.0"})
        with urllib.request.urlopen(request, timeout=120) as response:
            path.write_bytes(response.read())
    digest = hashlib.sha256(path.read_bytes()).hexdigest()
    if digest != SOURCE_SHA256:
        raise SystemExit(f"SHA-256 mismatch: {digest}; refusing to continue")
    return digest


def interval_summary(density):
    density = density / np.trapz(density, GRID)
    order = np.argsort(density)[::-1]
    step = GRID[1] - GRID[0]
    mass = np.cumsum(density[order]) * step
    inside = order[: np.searchsorted(mass, 0.683) + 1]
    cumulative = np.cumsum(density) * step
    return {"map": round(float(GRID[np.argmax(density)]), 2),
            "hpd68Lower": round(float(GRID[inside].min()), 2), "hpd68Upper": round(float(GRID[inside].max()), 2),
            "median": round(float(np.interp(0.5, cumulative, GRID)), 2), "mean": round(float(np.trapz(GRID * density, GRID)), 2)}


def posterior(distances, prior_power):
    """p(H0) proportional to H0^prior_power times the sample mean of the Gaussian velocity likelihood."""
    like = np.array([np.mean(np.exp(-0.5 * ((HUBBLE_FLOW_VELOCITY - h0 * distances) / HUBBLE_FLOW_SIGMA) ** 2)) for h0 in GRID])
    return like * GRID ** prior_power


def main(data_path, outputs_path):
    path = Path(data_path)
    digest = fetch(path)
    result = {"source": {"url": SOURCE_URL, "sha256": digest, "redistributed": False},
              "versions": {"python": platform.python_version(), "numpy": np.__version__, "scipy": scipy.__version__, "h5py": h5py.__version__},
              "inputs": {"hubbleFlowVelocity": HUBBLE_FLOW_VELOCITY, "hubbleFlowSigma": HUBBLE_FLOW_SIGMA, "units": "km/s and Mpc"},
              "published": {"reference": "Abbott et al. 2017, Nature 551, 85", "h0Map": 70.0, "upperError": 12.0, "lowerError": 8.0, "interval": "maximum a posteriori and minimal 68.3% interval, prior 1/H0"},
              "results": {}}
    with h5py.File(path, "r") as handle:
        for dataset in ("IMRPhenomPv2NRT_lowSpin_posterior", "IMRPhenomPv2NRT_highSpin_posterior"):
            distances = np.asarray(handle[dataset]["luminosity_distance_Mpc"], dtype=float)
            cosines = np.asarray(handle[dataset]["costheta_jn"], dtype=float)
            result["results"][dataset] = {
                "samples": int(distances.size),
                "distanceMedian": round(float(np.median(distances)), 2),
                "distance16": round(float(np.percentile(distances, 15.87)), 2), "distance84": round(float(np.percentile(distances, 84.13)), 2),
                "cosInclinationMedian": round(float(np.median(cosines)), 3),
                "priorInverseH0": interval_summary(posterior(distances, -1)),
                "priorFlat": interval_summary(posterior(distances, 0)),
            }
    json.dump(result, open(outputs_path, "w"), indent=2)
    print(json.dumps(result["results"], indent=1))


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])
