"""Flat Lambda-CDM distances and thin-plane lensing weights, in units of c/H0.

Independent of the Lab code: the comoving distance uses scipy's adaptive quadrature.
"""
import numpy as np
from scipy.integrate import quad


def comoving_distance(redshift, matter_density=0.3):
    """chi(z) = integral_0^z dz' / E(z'), E = sqrt(Om (1+z)^3 + 1 - Om)."""
    def inverse_hubble(z):
        return 1.0 / np.sqrt(matter_density * (1.0 + z) ** 3 + 1.0 - matter_density)
    value, _ = quad(inverse_hubble, 0.0, redshift, epsabs=1e-12, epsrel=1e-12)
    return value


def plane_weight(lens_redshift, source_redshift, matter_density=0.3):
    """Geometric weight of a thin lens plane for one source redshift.

    q = (1 + z_l) chi_l (chi_s - chi_l) / chi_s, the redshift-dependent part of the
    lensing kernel (Kilbinger 2015, Eqs. 21-24) for a single source plane. The constant
    3/2 Om (H0/c)^2 and the shell thickness are absorbed into each plane's field amplitude.
    Zero when the plane is behind the sources.
    """
    if lens_redshift >= source_redshift:
        return 0.0
    chi_lens = comoving_distance(lens_redshift, matter_density)
    chi_source = comoving_distance(source_redshift, matter_density)
    return (1.0 + lens_redshift) * chi_lens * (chi_source - chi_lens) / chi_source


def weight_matrix(lens_redshifts, source_redshifts, matter_density=0.3):
    """W[i, p]: weight of plane p for source bin i, normalised so the largest entry is one."""
    weights = np.array([[plane_weight(zl, zs, matter_density) for zl in lens_redshifts] for zs in source_redshifts])
    return weights / weights.max()
