"""Grid evaluation of the selection-corrected hierarchical likelihood (Mandel, Farr & Gair 2019).

For hyperparameters Lambda = (alpha, m_max) and N_obs events,

  log L(Lambda) = sum_i log[ (1/S_i) sum_s p_pop(theta_is | Lambda) / pi_PE(theta_is) ] - N_obs log xi(Lambda),

after marginalizing the merger rate with a 1/R prior. The detectable fraction is estimated from found
injections, xi = (1/N_draw) sum_found p_pop(theta_j | Lambda) / p_draw(theta_j), where N_draw counts
every generated injection, found or not.

The power-law factor m1^-alpha / Z(alpha, m_max) is the only part that depends on Lambda, so for each
alpha the sums over samples sorted by m1 become cumulative sums and every m_max costs one lookup.
"""
from dataclasses import dataclass

import numpy as np

from population_model import pe_prior_density, primary_normalization, redshift_density, secondary_density


@dataclass
class SortedWeights:
    """Samples sorted by primary mass with the Lambda-independent part of their weights."""

    primary: np.ndarray
    fixed_weight: np.ndarray


def event_weights(samples):
    m1, m2, z = samples[:, 0], samples[:, 1], samples[:, 2]
    fixed = secondary_density(m1, m2) * redshift_density(z) / pe_prior_density(z)
    order = np.argsort(m1)
    return SortedWeights(m1[order], fixed[order])


def injection_weights(injections):
    m1, m2, z, draw_pdf = injections[:, 0], injections[:, 1], injections[:, 2], injections[:, 3]
    fixed = secondary_density(m1, m2) * redshift_density(z) / draw_pdf
    order = np.argsort(m1)
    return SortedWeights(m1[order], fixed[order])


def _cumulative_sums(weights, alpha, m_max_grid):
    """Sums of w and w^2 over samples with m1 <= m_max, for one alpha and every m_max."""
    values = np.where(weights.primary > 0, weights.primary ** -alpha, 0.0) * weights.fixed_weight
    first = np.concatenate([[0.0], np.cumsum(values)])
    second = np.concatenate([[0.0], np.cumsum(values ** 2)])
    index = np.searchsorted(weights.primary, m_max_grid, side="right")
    return first[index], second[index]


def event_terms(weights, sample_count, alpha_grid, m_max_grid):
    """Monte Carlo event likelihood (up to a constant) and its effective sample size on the grid."""
    likelihood = np.zeros((len(alpha_grid), len(m_max_grid)))
    effective = np.zeros_like(likelihood)
    for row, alpha in enumerate(alpha_grid):
        total, squares = _cumulative_sums(weights, alpha, m_max_grid)
        normalization = primary_normalization(alpha, m_max_grid)
        likelihood[row] = total / (sample_count * normalization)
        effective[row] = np.where(squares > 0, total ** 2 / np.where(squares > 0, squares, 1), 0.0)
    return likelihood, effective


def selection_terms(weights, total_generated, alpha_grid, m_max_grid):
    """Detectable fraction xi, its Monte Carlo variance and Farr's (2019) effective count mu^2 / sigma^2."""
    fraction = np.zeros((len(alpha_grid), len(m_max_grid)))
    variance = np.zeros_like(fraction)
    for row, alpha in enumerate(alpha_grid):
        total, squares = _cumulative_sums(weights, alpha, m_max_grid)
        normalization = primary_normalization(alpha, m_max_grid)
        mean = total / (total_generated * normalization)
        fraction[row] = mean
        variance[row] = squares / (total_generated * normalization) ** 2 - mean ** 2 / total_generated
    effective = np.where(variance > 0, fraction ** 2 / np.where(variance > 0, variance, 1), 0.0)
    return fraction, variance, effective


def normalized_posterior(log_posterior, valid):
    finite = np.where(valid & np.isfinite(log_posterior), log_posterior, -np.inf)
    peak = np.max(finite)
    posterior = np.exp(finite - peak)
    return posterior / posterior.sum()


def marginal_summary(axis_values, marginal):
    cumulative = np.cumsum(marginal) / np.sum(marginal)
    quantile = lambda level: float(np.interp(level, cumulative, axis_values))
    return {"median": quantile(0.5), "lower90": quantile(0.05), "upper90": quantile(0.95)}


def truth_percentile(axis_values, marginal, truth):
    """Posterior probability mass below the true value (linear interpolation of the grid CDF)."""
    cumulative = np.cumsum(marginal) / np.sum(marginal)
    return float(np.interp(truth, axis_values, cumulative))
