"""Restricted population model used by the AC60 hierarchical inference.

Source-frame primary mass m1 follows a power law m1^-alpha between M_MIN and a sharp maximum m_max.
The secondary follows p(m2 | m1) ∝ m2^beta on [M_MIN, m1] (equivalent to q^beta). Mergers are spread
as p(z) ∝ dVc/dz (1+z)^(kappa-1) on [0, Z_MAX]. Only alpha and m_max are inferred; beta and kappa
are fixed at the GWTC-3 POWER LAW+PEAK median beta_q = 1.1 and kappa = 2.7.

Units: masses in solar masses, distances in Mpc, redshift dimensionless.
"""
import numpy as np

M_MIN = 5.0
BETA = 1.1
KAPPA = 2.7
Z_MAX = 1.9  # maximum redshift of the O3 injection campaign

# Flat matter + Lambda cosmology. H0 = 67.74 km/s/Mpc with Omega_m = 0.3089 reproduces the comoving
# distances stored with the GWTC-3 PE prior samples to about 1e-4 (checked in docs/astronomy/ac60).
HUBBLE_CONSTANT = 67.74
OMEGA_MATTER = 0.3089
SPEED_OF_LIGHT_KM_S = 299792.458
HUBBLE_DISTANCE_MPC = SPEED_OF_LIGHT_KM_S / HUBBLE_CONSTANT

_redshift_grid = np.linspace(0.0, 3.0, 30001)
_inverse_expansion = 1.0 / np.sqrt(OMEGA_MATTER * (1 + _redshift_grid) ** 3 + 1 - OMEGA_MATTER)
_comoving_grid = HUBBLE_DISTANCE_MPC * np.concatenate(
    [[0.0], np.cumsum(0.5 * (_inverse_expansion[1:] + _inverse_expansion[:-1]) * np.diff(_redshift_grid))]
)


def comoving_distance(z):
    return np.interp(z, _redshift_grid, _comoving_grid)


def comoving_volume_density(z):
    """dVc/dz in Mpc^3 over the whole sky."""
    expansion = np.sqrt(OMEGA_MATTER * (1 + z) ** 3 + 1 - OMEGA_MATTER)
    return 4 * np.pi * HUBBLE_DISTANCE_MPC * comoving_distance(z) ** 2 / expansion


def _redshift_normalization():
    z = np.linspace(0.0, Z_MAX, 20001)
    density = comoving_volume_density(z) * (1 + z) ** (KAPPA - 1)
    return np.sum(0.5 * (density[1:] + density[:-1]) * np.diff(z))


REDSHIFT_NORMALIZATION = _redshift_normalization()


def redshift_density(z):
    inside = (z >= 0) & (z <= Z_MAX)
    return np.where(inside, comoving_volume_density(z) * (1 + z) ** (KAPPA - 1) / REDSHIFT_NORMALIZATION, 0.0)


def secondary_density(m1, m2):
    """p(m2 | m1) ∝ m2^BETA on [M_MIN, m1]."""
    inside = (m2 >= M_MIN) & (m2 <= m1) & (m1 > M_MIN)
    safe_m1 = np.where(inside, m1, 2 * M_MIN)
    normalization = (safe_m1 ** (BETA + 1) - M_MIN ** (BETA + 1)) / (BETA + 1)
    return np.where(inside, np.where(inside, m2, M_MIN) ** BETA / normalization, 0.0)


def primary_normalization(alpha, m_max):
    """Integral of m^-alpha from M_MIN to m_max (arrays broadcast)."""
    alpha = np.asarray(alpha, dtype=float)
    near_one = np.abs(alpha - 1) < 1e-9
    safe = np.where(near_one, 2.0, alpha)
    power = (np.asarray(m_max, dtype=float) ** (1 - safe) - M_MIN ** (1 - safe)) / (1 - safe)
    return np.where(near_one, np.log(np.asarray(m_max, dtype=float) / M_MIN), power)


def population_density(m1, m2, z, alpha, m_max):
    """Normalized p(m1, m2, z | alpha, m_max) for scalar hyperparameters."""
    primary = np.where((m1 >= M_MIN) & (m1 <= m_max), m1 ** -alpha, 0.0) / primary_normalization(alpha, m_max)
    return primary * secondary_density(m1, m2) * redshift_density(z)


def pe_prior_density(z):
    """GWTC-3 *_cosmo samples: uniform in detector-frame component masses and p(z) ∝ dVc/dz / (1+z).

    The Jacobian from detector-frame to source-frame masses is (1+z)^2, so the prior on
    (m1_source, m2_source, z) is proportional to (1+z) dVc/dz, up to a constant.
    """
    return (1 + z) * comoving_volume_density(z)
