"""Restricted standard-siren model shared by the Sandbox Physics tutorial scripts.

Units: distances in Mpc, velocities in km/s, H0 in km/s/Mpc. Flat Lambda-CDM with Omega_m = 0.3.
Record: the two leading-order polarisation amplitudes of a circular inspiral (Cutler & Flanagan 1994, Eq. 62),
    a_plus  = s (1 + v^2) / 2 / D + n_plus,   a_cross = s v / D + n_cross,   v = cos(inclination),
with unit Gaussian noise and s = rho100 * 100 / sqrt(2), so the face-on optimal SNR at 100 Mpc is rho100.
Polarisation angle, phase and the detector-frame chirp mass are treated as known. This is a teaching model,
not a parameter-estimation code for real detector data.
"""
import numpy as np
from scipy import stats
from scipy.integrate import cumulative_trapezoid

SPEED_OF_LIGHT = 299792.458
MATTER_DENSITY = 0.3
CATALOG_MAX_REDSHIFT = 0.07
DETECTION_THRESHOLD = 12.0

_z_table = np.linspace(0.0, 0.3, 30001)
_chi_table = cumulative_trapezoid(1.0 / np.sqrt(MATTER_DENSITY * (1 + _z_table) ** 3 + 1 - MATTER_DENSITY), _z_table, initial=0.0)


def luminosity_distance(z, h0):
    """D_L in Mpc for redshift z and H0."""
    z = np.asarray(z, dtype=float)
    return (1 + z) * SPEED_OF_LIGHT * np.interp(z, _z_table, _chi_table) / h0


def volume_weight(z):
    """Comoving volume density per unit redshift, chi^2 / E(z), zero outside (0, z_max]. Unnormalised."""
    z = np.asarray(z, dtype=float)
    chi = np.interp(z, _z_table, _chi_table)
    weight = chi ** 2 / np.sqrt(MATTER_DENSITY * (1 + z) ** 3 + 1 - MATTER_DENSITY)
    return np.where((z > 0) & (z <= CATALOG_MAX_REDSHIFT), weight, 0.0)


_volume_z = np.linspace(0.0, CATALOG_MAX_REDSHIFT, 4001)
_volume_cdf = cumulative_trapezoid(volume_weight(_volume_z), _volume_z, initial=0.0)
_volume_cdf /= _volume_cdf[-1]


def draw_volume_redshifts(rng, size):
    """Redshifts drawn uniformly in comoving volume out to the catalog edge (inverse CDF)."""
    return np.interp(rng.random(size), _volume_cdf, _volume_z)


def amplitude_scale(rho100):
    return rho100 * 100.0 / np.sqrt(2.0)


def optimal_snr(distance, cosine, rho100):
    return amplitude_scale(rho100) * np.hypot(0.5 * (1 + cosine ** 2), cosine) / distance


def simulate_record(rng, distance, cosine, rho100):
    scale = amplitude_scale(rho100) / distance
    plus = scale * 0.5 * (1 + cosine ** 2) + rng.standard_normal()
    cross = scale * cosine + rng.standard_normal()
    return plus, cross


def detection_probability_for_snr(snr):
    """P(observed SNR > threshold): observed SNR^2 is non-central chi-square with 2 degrees of freedom."""
    snr = np.asarray(snr, dtype=float)
    return stats.ncx2.sf(DETECTION_THRESHOLD ** 2, df=2, nc=snr ** 2)


COSINE_GRID = np.linspace(0.0, 1.0, 201)
DISTANCE_GRID = np.geomspace(2.0, 4000.0, 1200)
HUBBLE_GRID = np.linspace(20.0, 160.0, 281)


def detection_probability_at_distance(distance, rho100):
    """P_det(D), averaged over cos(inclination) uniform on [0, 1]."""
    distance = np.atleast_1d(np.asarray(distance, dtype=float))
    snr = optimal_snr(distance[:, None], COSINE_GRID[None, :], rho100)
    return np.trapz(detection_probability_for_snr(snr), COSINE_GRID, axis=1)


def distance_likelihood(plus, cross, rho100):
    """Marginal likelihood of the record on DISTANCE_GRID (flat prior on cos(inclination)), max scaled to 1."""
    scale = amplitude_scale(rho100) / DISTANCE_GRID[:, None]
    residual = (plus - scale * 0.5 * (1 + COSINE_GRID ** 2)) ** 2 + (cross - scale * COSINE_GRID) ** 2
    log_like = -0.5 * residual
    peak = log_like.max()
    marginal = np.trapz(np.exp(log_like - peak), COSINE_GRID, axis=1)
    return marginal / marginal.max()


def likelihood_at(table, distance):
    return np.interp(np.log(distance), np.log(DISTANCE_GRID), table, left=0.0, right=0.0)


def redshift_nodes(measured_velocity, sigma_v, count=81, half_width=5.0):
    """Nodes and normalised weights of p(z | measured velocity), proportional to N(v; c z, sigma_v) p_vol(z)."""
    offsets = np.linspace(-half_width, half_width, count)
    z = (np.asarray(measured_velocity, dtype=float)[..., None] + sigma_v * offsets) / SPEED_OF_LIGHT
    weight = np.exp(-0.5 * offsets ** 2) * volume_weight(z)
    total = weight.sum(axis=-1, keepdims=True)
    return z, np.divide(weight, total, out=np.zeros_like(weight), where=total > 0)


def volume_selection(rho100, h0_grid=HUBBLE_GRID):
    """beta(H0) = integral P_det(D_L(z, H0)) p_vol(z) dz, for a counterpart analysis."""
    z = np.linspace(1e-5, CATALOG_MAX_REDSHIFT, 1500)
    p_vol = volume_weight(z)
    p_vol = p_vol / np.trapz(p_vol, z)
    d_grid = np.geomspace(0.5, 8000.0, 1500)
    pdet_grid = detection_probability_at_distance(d_grid, rho100)
    pdet = np.interp(np.log(luminosity_distance(z[None, :], h0_grid[:, None])), np.log(d_grid), pdet_grid)
    return np.trapz(pdet * p_vol, z, axis=1)


def catalog_selection(z_nodes, weights, rho100, h0_grid=HUBBLE_GRID):
    """beta(H0) averaged over the catalog galaxies' p(z | v_i), for a dark-siren analysis."""
    d_grid = np.geomspace(0.5, 8000.0, 1500)
    pdet_grid = detection_probability_at_distance(d_grid, rho100)
    unit = luminosity_distance(np.clip(z_nodes, 0, None), 1.0)
    result = np.empty(h0_grid.size)
    for index, h0 in enumerate(h0_grid):
        pdet = np.interp(np.log(np.maximum(unit / h0, 1e-6)), np.log(d_grid), pdet_grid)
        result[index] = np.mean(np.sum(weights * pdet, axis=-1))
    return result


def galaxy_likelihoods(table, z_nodes, weights, h0_grid=HUBBLE_GRID):
    """Matrix [galaxy, H0] of the expected distance likelihood over each galaxy's p(z | v)."""
    unit = luminosity_distance(np.clip(z_nodes, 0, None), 1.0)
    out = np.empty((z_nodes.shape[0], h0_grid.size))
    for index, h0 in enumerate(h0_grid):
        out[:, index] = np.sum(weights * likelihood_at(table, np.maximum(unit / h0, 1e-6)), axis=-1)
    return out


def normalise(values, grid=HUBBLE_GRID):
    area = np.trapz(values, grid)
    return values / area if area > 0 else values


def cdf_at(density, value, grid=HUBBLE_GRID):
    """Posterior CDF at value; NaN when the density vanishes on the whole grid."""
    cumulative = cumulative_trapezoid(density, grid, initial=0.0)
    if not cumulative[-1] > 0:
        return float("nan")
    return float(np.interp(value, grid, cumulative / cumulative[-1]))


def summarise(density, grid=HUBBLE_GRID):
    cumulative = cumulative_trapezoid(density, grid, initial=0.0)
    cumulative /= cumulative[-1]
    lower, median, upper = np.interp([0.1587, 0.5, 0.8413], cumulative, grid)
    return {"median": round(float(median), 3), "lower": round(float(lower), 3), "upper": round(float(upper), 3)}
