"""Independent checks of the kilonova light-curve model.

None of these checks reuses the Arnett recurrence it tests:

1. energy equation: integrate dE/dt = Q - E/t - L with L = 2 E t / td^2 using
   scipy's implicit Radau solver and compare with the recurrence;
2. energy budget: deposited energy = radiated + adiabatic loss + energy left;
3. Arnett's rule: L equals the deposited power at the light-curve peak;
4. self-similar peak: for pure power-law heating, t_peak / td solves
   2 exp(-x^2) Int_0^x u^(1-alpha) exp(u^2) du = x^(-alpha), found here by
   quadrature and root finding;
5. diffusion-time scaling against the random-walk estimate of Metzger (2019, eq. 7);
6. radioactive energy integral against the closed form for a power law and the
   published rate of Metzger (2019, eq. 23);
7. blackbody normalisation: Int F_nu dnu * 4 pi D^2 equals L.

Run: python check_independent_limits.py  (writes independent-checks.json)
"""
import json
import math
from pathlib import Path

import numpy as np
from scipy.integrate import quad, solve_ivp
from scipy.optimize import brentq

import kilonova_model as model

HERE = Path(__file__).resolve().parent
RED = (0.050, 0.149, 3.65, 1151.0)   # Villar et al. 2017, Table 2, two-component red row
BLUE = (0.023, 0.256, 0.5, 3983.0)


def energy_equation_check(component):
    mass, velocity, opacity, _ = component
    diffusion = model.diffusion_time_days(mass, velocity, opacity)
    grid = model.time_grid()
    deposited = model.deposited_power(grid, mass, velocity)
    recurrence = model.arnett_luminosity(grid, deposited, diffusion)

    def power(t):
        return float(model.deposited_power(np.array([t]), mass, velocity)[0])

    def derivative(t, state):
        energy = state[0]  # erg, times in days so rates are per day
        luminosity = 2.0 * energy * t / diffusion ** 2
        return [power(t) * model.SECONDS_PER_DAY - energy / t - luminosity]

    start = 1e-4
    sample = np.geomspace(0.3, 30.0, 60)
    solution = solve_ivp(derivative, (start, 30.0), [0.0], method='Radau', rtol=1e-10, atol=1e25, t_eval=sample)
    energy = solution.y[0]
    luminosity_ode = 2.0 * energy * sample / diffusion ** 2 / model.SECONDS_PER_DAY
    luminosity_recurrence = np.interp(sample, grid, recurrence)
    worst = float(np.max(np.abs(luminosity_recurrence / luminosity_ode - 1.0)))

    # Budget on the recurrence: Int Q dt = Int L dt + Int E/t dt + E(end), with E = L td^2 / (2 t).
    seconds = grid * model.SECONDS_PER_DAY
    energy_from_l = recurrence * (diffusion * model.SECONDS_PER_DAY) ** 2 / (2.0 * seconds)
    deposited_total = np.trapezoid(deposited, seconds)
    radiated = np.trapezoid(recurrence, seconds)
    adiabatic = np.trapezoid(energy_from_l / seconds, seconds)
    closure = (radiated + adiabatic + energy_from_l[-1]) / deposited_total - 1.0

    index = int(np.argmax(recurrence))
    window = slice(index - 2, index + 3)
    coefficients = np.polyfit(np.log(grid[window]), recurrence[window], 2)
    peak_time = math.exp(-coefficients[1] / (2 * coefficients[0]))
    peak_luminosity = float(np.polyval(coefficients, math.log(peak_time)))
    arnett_ratio = peak_luminosity / float(model.deposited_power(np.array([peak_time]), mass, velocity)[0])
    return {
        'diffusionDays': round(diffusion, 4),
        'maxRelativeDifferenceOdeVsRecurrence': round(worst, 6),
        'energyBudgetClosure': round(float(closure), 6),
        'radiatedFraction': round(float(radiated / deposited_total), 5),
        'peakDays': round(peak_time, 4),
        'arnettRatioAtPeak': round(float(arnett_ratio), 5),
    }


def self_similar_peak(alpha=1.3):
    def condition(x):
        integral, _ = quad(lambda u: u ** (1 - alpha) * math.exp(u * u - x * x), 0.0, x, limit=200)
        return 2.0 * integral - x ** (-alpha)
    x_peak = brentq(condition, 0.3, 3.0, xtol=1e-12)
    grid = np.geomspace(1e-6, 60.0, 6000)  # start early: the t^-1.3 source deposits energy before 1e-3 d
    measured = []
    for opacity in (0.5, 2.0, 8.0):
        diffusion = model.diffusion_time_days(0.02, 0.2, opacity)
        heating = grid ** (-alpha)          # pure power law, thermalization switched off
        luminosity = model.arnett_luminosity(grid, heating, diffusion)
        index = int(np.argmax(luminosity))
        window = slice(index - 2, index + 3)
        coefficients = np.polyfit(np.log(grid[window]), luminosity[window], 2)
        peak = math.exp(-coefficients[1] / (2 * coefficients[0]))
        measured.append({'opacity': opacity, 'diffusionDays': round(diffusion, 5), 'peakDays': round(peak, 5), 'peakOverDiffusion': round(peak / diffusion, 5)})
    slope = math.log(measured[-1]['peakDays'] / measured[0]['peakDays']) / math.log(8.0 / 0.5)
    return {'alpha': alpha, 'quadraturePeakOverDiffusion': round(x_peak, 6), 'model': measured, 'peakTimeOpacityExponent': round(slope, 5)}


def random_walk_scaling():
    """Metzger 2019 eq. (7): t_peak = sqrt(3 M kappa / (4 pi beta' v c)) with beta' = 3 gives 1.6 d for M = 0.01 Msun, v = 0.1c, kappa = 1."""
    mass = 0.01 * model.SOLAR_MASS
    velocity = 0.1 * model.SPEED_OF_LIGHT
    random_walk = math.sqrt(3 * mass * 1.0 / (4 * math.pi * 3.0 * velocity * model.SPEED_OF_LIGHT)) / model.SECONDS_PER_DAY
    arnett = model.diffusion_time_days(0.01, 0.1, 1.0)
    exponents = {}
    for name, factor in (('mass', (0.04, 0.1, 1.0)), ('velocity', (0.01, 0.4, 1.0)), ('opacity', (0.01, 0.1, 4.0))):
        exponents[name] = round(math.log(model.diffusion_time_days(*factor) / arnett) / math.log(4.0), 6)
    return {'metzgerEq7Days': round(random_walk, 4), 'publishedValueDays': 1.6, 'arnettDiffusionDays': round(arnett, 4),
            'ratioArnettToRandomWalk': round(arnett / random_walk, 5), 'analyticRatio': round(math.sqrt(2 * 4 * math.pi * 3.0 / (3 * model.BETA)), 5),
            'diffusionExponents': exponents}


def radioactive_energy():
    sigma, t0 = model.HEATING_SIGMA_SECONDS, model.HEATING_T0_SECONDS
    amplitude = model.HEATING_NORMALIZATION * (sigma / math.pi) ** model.HEATING_EXPONENT
    start, stop = 1 * model.SECONDS_PER_DAY, 10 * model.SECONDS_PER_DAY
    numerical, _ = quad(lambda s: float(model.heating_per_gram(s / model.SECONDS_PER_DAY)), start, stop, limit=200)
    closed = amplitude * (start ** -0.3 - stop ** -0.3) / 0.3
    at_one_day = float(model.heating_per_gram(1.0))
    return {'integralOneToTenDaysErgPerGram': float('%.6e' % numerical), 'closedFormPowerLaw': float('%.6e' % closed),
            'relativeDifference': round(numerical / closed - 1.0, 6), 'heatingAtOneDayErgPerGramPerSecond': float('%.5e' % at_one_day),
            'metzgerEq23': 2.0e10, 'ratioToMetzgerEq23': round(at_one_day / 2.0e10, 5)}


def blackbody_normalisation():
    distance = 39.5 * model.MEGAPARSEC
    results = []
    for temperature, radius in ((5000.0, 4e14), (1150.0, 1.2e15)):
        luminosity = 4 * math.pi * radius ** 2 * model.STEFAN_BOLTZMANN * temperature ** 4
        peak = 5.879e10 * temperature
        integral, _ = quad(lambda nu: float(model.blackbody_flux_density(nu, temperature, radius, distance)), 1e-4 * peak, 30 * peak, limit=400)
        results.append({'temperature': temperature, 'ratio': round(integral * 4 * math.pi * distance ** 2 / luminosity, 6)})
    return results


def main():
    output = {
        'description': 'Independent checks of the grey kilonova model; see the docstring of check_independent_limits.py.',
        'energyEquation': {'red': energy_equation_check(RED), 'blue': energy_equation_check(BLUE)},
        'selfSimilarPeak': self_similar_peak(),
        'diffusionScaling': random_walk_scaling(),
        'radioactiveEnergy': radioactive_energy(),
        'blackbodyNormalisation': blackbody_normalisation(),
    }
    (HERE / 'independent-checks.json').write_text(json.dumps(output, indent=1) + '\n')
    print(json.dumps(output, indent=1))


if __name__ == '__main__':
    main()
