"""Hydrostatic masses from frozen X-COP density and pressure profiles.

For one cluster:
1. fit the deprojected electron density with the Vikhlinin et al. (2006) Eq. (3)
   form (one core component, gamma = 3);
2. fit the electron pressure, all X-ray and SZ points jointly, with a
   generalised NFW profile (Arnaud et al. 2010 Eq. 11) with the inner slope fixed
   at 0.3081 and one free scale factor on the SZ points;
3. compute M_HSE(<r) = -r^2 dP_e/dr / (G mu m_p n_e) with mu = 0.61;
4. find R500 where the mean enclosed density is 500 rho_c(z), flat LCDM with
   H0 = 70 and Omega_m = 0.3;
5. integrate the gas mass with rho_gas = mu m_p (n_e + n_p), n_e = 1.17 n_p
   (Eckert et al. 2019, Sect. 2) and compare f_gas with 0.131;
6. form two more mass estimates from the same profiles: the mass at which the
   gas fraction would equal the universal 0.131, and the mass that the Planck
   2015 XXIV Eq. (7) X-ray-calibrated Y-M relation assigns to our Y500
   (log10 Y* = -0.19, alpha = 1.79, beta = 0.66, h = 0.7, spherical Y500 per Sec. 1).

This is a simplified re-analysis, not the X-COP pipeline: the published masses
come from forward-fitting with covariance matrices that this script ignores.
"""
import json
import math

import numpy as np
from scipy.optimize import brentq, curve_fit

KILOPARSEC_CM = 3.0856775814913673e21
PROTON_MASS_KG = 1.67262192369e-27
GRAVITATIONAL_CONSTANT_SI = 6.6743e-11
SOLAR_MASS_KG = 1.98840987e30
KEV_JOULE = 1.602176634e-16
MEAN_MOLECULAR_WEIGHT = 0.61
GAS_MASS_PER_ELECTRON_IN_PROTON_MASSES = MEAN_MOLECULAR_WEIGHT * (1 + 1 / 1.17)
INNER_PRESSURE_SLOPE = 0.3081
UNIVERSAL_GAS_FRACTION = 0.131
PLANCK_LOG10_Y_STAR, PLANCK_MASS_SLOPE, PLANCK_REDSHIFT_SLOPE = -0.19, 1.79, 0.66


def critical_density_kg_m3(redshift, hubble=70.0, omega_matter=0.3):
    hubble_per_second = hubble * 1000 / (KILOPARSEC_CM / 100 * 1000) * math.sqrt(omega_matter * (1 + redshift) ** 3 + 1 - omega_matter)
    return 3 * hubble_per_second ** 2 / (8 * math.pi * GRAVITATIONAL_CONSTANT_SI)


def log_density_model(radius, log_norm, core, slope, beta, steep_radius, steepening):
    x = radius / core
    return log_norm + 0.5 * (-slope * np.log(x) - (3 * beta - slope / 2) * np.log1p(x * x)
                             - (steepening / 3) * np.log1p((radius / steep_radius) ** 3))


def log_pressure_model(scaled_radius, log_amplitude, concentration, outer_alpha, outer_beta):
    cx = concentration * scaled_radius
    return log_amplitude - INNER_PRESSURE_SLOPE * np.log(cx) - ((outer_beta - INNER_PRESSURE_SLOPE) / outer_alpha) * np.log1p(cx ** outer_alpha)


def fit_density(record):
    density = record["density"]
    radius = 0.5 * (np.array(density["R_IN"]) + np.array(density["R_OUT"]))
    value = np.array(density["NE"])
    sigma = 0.5 * (np.array(density["NE_HIGH"]) - np.array(density["NE_LOW"])) / value
    start = [math.log(0.01), 100.0, 0.5, 0.6, 1500.0, 3.0]
    bounds = ([math.log(1e-5), 5, 0, 0.2, 300, 0], [math.log(1.0), 1000, 2.5, 1.5, 6000, 8])
    parameters, _ = curve_fit(log_density_model, radius, np.log(value), p0=start, sigma=sigma, bounds=bounds, maxfev=40000)
    residual = (np.log(value) - log_density_model(radius, *parameters)) / sigma
    return parameters, float(np.sum(residual ** 2)), len(radius)


def sz_unit_check(record):
    """The SZ table header reads P/K500. Compare SZ and X-ray points where they overlap to see whether both are P/P500."""
    xray, sz = record["pressureXRay"], record["pressureSZ"]
    ratios = []
    for radius, value in zip(sz["RW_SZ"], sz["P_SZ"]):
        if xray["RW_X"][0] <= radius <= xray["RW_X"][-1]:
            ratios.append(value / float(np.exp(np.interp(math.log(radius), np.log(xray["RW_X"]), np.log(xray["P_X"])))))
    return float(np.median(ratios)), len(ratios)


def fit_pressure(record, excluded_inner_sz_points=0, fit_scale=True):
    """Fit X-ray and SZ pressure with optional core exclusion and relative scaling.

    The SZ points get one free scale factor. In the overlap region the frozen SZ
    table sits 8-25 % below the X-ray points for these two clusters (see
    sz_unit_check), and a single gNFW shape cannot pass through both sets. The
    scale factor absorbs that offset so the SZ points constrain only the outer
    slope, which is what the hydrostatic mass needs.
    """
    xray, sz = record["pressureXRay"], record["pressureSZ"]
    radius = np.array(xray["RW_X"] + sz["RW_SZ"][excluded_inner_sz_points:])
    value = np.array(xray["P_X"] + sz["P_SZ"][excluded_inner_sz_points:])
    error = np.array(xray["eP_X"] + sz["eP_SZ"][excluded_inner_sz_points:])
    is_sz = np.array([0.0] * len(xray["RW_X"]) + [1.0] * (len(radius) - len(xray["RW_X"])))
    index = np.arange(len(radius), dtype=float)

    def model(point_index, log_amplitude, concentration, outer_alpha, outer_beta, log_sz_scale=0.0):
        selected = point_index.astype(int)
        return log_pressure_model(radius[selected], log_amplitude, concentration, outer_alpha, outer_beta) + log_sz_scale * is_sz[selected]

    bounds = ([math.log(0.1), 0.05, 0.3, 2.5, -1.0], [math.log(500), 8, 5, 12, 1.0])
    start = [math.log(8), 1.2, 1.0, 5.0, 0.0]
    if not fit_scale:
        bounds = (bounds[0][:4], bounds[1][:4])
        start = start[:4]
    parameters, _ = curve_fit(model, index, np.log(value), p0=start, sigma=error / value, bounds=bounds, maxfev=40000)
    residual = (np.log(value) - model(index, *parameters)) / (error / value)
    return parameters[:4], float(math.exp(parameters[4])) if fit_scale else 1.0, float(np.sum(residual ** 2)), len(radius)


def analyse_cluster(record, *, aperture_kpc=None, excluded_inner_sz_points=0, fit_scale=True):
    header = record["header"]
    radius500_published = header["radius500Kiloparsec"]
    pressure500 = header["pressure500KiloElectronVoltsPerCubicCentimetre"]
    density_parameters, density_chi_square, density_points = fit_density(record)
    pressure_parameters, sz_scale, pressure_chi_square, pressure_points = fit_pressure(record, excluded_inner_sz_points, fit_scale)

    def electron_density(radius_kpc):
        return math.exp(log_density_model(radius_kpc, *density_parameters))

    def electron_pressure(radius_kpc):
        return pressure500 * math.exp(log_pressure_model(radius_kpc / radius500_published, *pressure_parameters))

    def pressure_log_slope(radius_kpc):
        step = 1e-3
        return (math.log(electron_pressure(radius_kpc * (1 + step))) - math.log(electron_pressure(radius_kpc * (1 - step)))) / (math.log1p(step) - math.log1p(-step))

    def hydrostatic_mass(radius_kpc):
        slope = pressure_log_slope(radius_kpc)
        pressure_si = electron_pressure(radius_kpc) * KEV_JOULE * 1e6
        density_si = electron_density(radius_kpc) * 1e6
        radius_m = radius_kpc * KILOPARSEC_CM / 100
        return -slope * pressure_si * radius_m / (GRAVITATIONAL_CONSTANT_SI * MEAN_MOLECULAR_WEIGHT * PROTON_MASS_KG * density_si) / SOLAR_MASS_KG

    rho_c = critical_density_kg_m3(header["redshift"])

    def mass_excess(radius_kpc):
        radius_m = radius_kpc * KILOPARSEC_CM / 100
        return hydrostatic_mass(radius_kpc) * SOLAR_MASS_KG - 500 * rho_c * 4 / 3 * math.pi * radius_m ** 3

    radius500 = brentq(mass_excess, 500, 3000)
    mass500 = hydrostatic_mass(radius500)

    def gas_mass(radius_kpc):
        grid = np.geomspace(1.0, radius_kpc, 2000)
        integrand = np.array([4 * math.pi * r ** 2 * electron_density(r) for r in grid])
        electrons = float(np.sum(0.5 * (integrand[1:] + integrand[:-1]) * np.diff(grid))) * KILOPARSEC_CM ** 3
        return electrons * GAS_MASS_PER_ELECTRON_IN_PROTON_MASSES * PROTON_MASS_KG / SOLAR_MASS_KG

    gas_fraction = gas_mass(radius500) / mass500

    def gas_fraction_excess(radius_kpc):
        radius_m = radius_kpc * KILOPARSEC_CM / 100
        return gas_mass(radius_kpc) / UNIVERSAL_GAS_FRACTION - 500 * rho_c * 4 / 3 * math.pi * radius_m ** 3 / SOLAR_MASS_KG

    radius500_gas_fraction = brentq(gas_fraction_excess, 500, 3000, xtol=0.01)
    mass500_gas_fraction = gas_mass(radius500_gas_fraction) / UNIVERSAL_GAS_FRACTION
    compton500 = spherical_compton(electron_pressure, radius500)
    evolution = math.sqrt(0.3 * (1 + header["redshift"]) ** 3 + 0.7)
    mass500_planck_relation = 6e14 * (compton500 / (1e-4 * 10 ** PLANCK_LOG10_Y_STAR * evolution ** PLANCK_REDSHIFT_SLOPE)) ** (1 / PLANCK_MASS_SLOPE)
    published_fraction = float(np.interp(1.0, record["gasFraction"]["RADIUS"], record["gasFraction"]["FGAS"]))
    sz_ratio, sz_overlap = sz_unit_check(record)
    profile = [{"radiusOverR500": x, "hydrostaticMass": hydrostatic_mass(x * radius500_published)} for x in (0.3, 0.5, 1.0, 1.5)]
    result = {
        "cluster": record["cluster"],
        "densityFit": {"parameters": [float(v) for v in density_parameters], "chiSquare": density_chi_square, "points": density_points},
        "pressureFit": {"parameters": [float(v) for v in pressure_parameters], "szScaleFactor": sz_scale, "chiSquare": pressure_chi_square, "points": pressure_points},
        "pressureLogSlopeAtR500": pressure_log_slope(radius500),
        "szOverXRayPressureMedianRatio": sz_ratio,
        "szOverlapPoints": sz_overlap,
        "radius500Kiloparsec": radius500,
        "mass500": mass500,
        "publishedRadius500Kiloparsec": radius500_published,
        "publishedMass500": header["mass500InUnitsOf1e14SolarMasses"] * 1e14,
        "massRatioToPublished": mass500 / (header["mass500InUnitsOf1e14SolarMasses"] * 1e14),
        "gasMass500": gas_mass(radius500),
        "gasFraction500": gas_fraction,
        "publishedGasFractionAtPublishedR500": published_fraction,
        "constantAlphaEstimate": 1 - UNIVERSAL_GAS_FRACTION / gas_fraction,
        "electronPressureAtR500": electron_pressure(radius500),
        "hydrostaticMassProfile": profile,
        "sphericalCompton500Mpc2": compton500,
        "mass500FromUniversalGasFraction": mass500_gas_fraction,
        "mass500FromPlanckYMRelation": mass500_planck_relation,
        "hydrostaticOverGasFractionMass": mass500 / mass500_gas_fraction,
    }
    if aperture_kpc is not None:
        published = record["gasFraction"]
        radius = aperture_kpc / radius500_published
        if not published["RADIUS"][0] <= radius <= published["RADIUS"][-1]:
            raise ValueError("Requested aperture lies outside the published hydrostatic mass profile")
        result["fixedAperture"] = {
            "radiusKiloparsec": aperture_kpc,
            "fittedHydrostaticMass": hydrostatic_mass(aperture_kpc),
            "publishedHydrostaticMass": math.exp(np.interp(math.log(radius), np.log(published["RADIUS"]), np.log(published["M_NFW"]))),
            "sphericalComptonMpc2": spherical_compton(electron_pressure, aperture_kpc),
        }
    return result


def spherical_compton(pressure_function, radius_kpc):
    """Y_sph(<R) = sigma_T / (m_e c^2) * int 4 pi r^2 P_e dr, in Mpc^2."""
    thomson_cm2, electron_rest_kev = 6.6524587321e-25, 510.99895
    grid = np.geomspace(1.0, radius_kpc, 3000)
    integrand = np.array([4 * math.pi * r ** 2 * pressure_function(r) for r in grid])
    integral = float(np.sum(0.5 * (integrand[1:] + integrand[:-1]) * np.diff(grid))) * KILOPARSEC_CM ** 3
    return thomson_cm2 / electron_rest_kev * integral / (1000 * KILOPARSEC_CM) ** 2


def load(path):
    with open(path, encoding="utf-8") as handle:
        return json.load(handle)
