"""Grey-opacity, multi-component kilonova light curves (reference implementation).

The model follows Villar et al. 2017 (arXiv:1710.11576v2, Section 3, eqs. 1-5), which
uses the Metzger 2017 / MOSFiT formulation:

* radioactive heating per gram (Korobkin et al. 2012, eq. 4)
      q(t) = 4e18 * [0.5 - arctan((t - t0) / sigma) / pi]^1.3   erg/s/g,
  with t0 = 1.3 s and sigma = 0.11 s;
* thermalization efficiency (Barnes et al. 2016, eq. 36 and Table 1)
      eps(t) = 0.36 * [exp(-a t) + ln(1 + 2 b t^d) / (2 b t^d)],  t in days,
  with (a, b, d) interpolated bilinearly in (log10 M, v) inside the table
  and clamped to its edges outside it;
* Arnett diffusion for a central source,
      L(t) = (2 / td^2) exp(-t^2/td^2) * Integral_0^t Q(t') t' exp(t'^2/td^2) dt',
      td = sqrt(2 kappa M / (beta v c)),  beta = 13.4.
  Villar et al. (eq. 3) print the kernel t/td in place of 2t/td^2. That form
  has units of energy, not power; the factor 2/td is restored here and checked
  in check_independent_limits.py against Arnett's rule and the energy equation;
* a blackbody photosphere at R = v t with a temperature floor Tc. Villar et
  al. print sigma_SB squared inside the Stefan-Boltzmann relation; the
  dimensionally correct T = (L / (4 pi sigma_SB R^2))^(1/4) is used here.

All quantities are CGS unless a name says otherwise. Times are in days.
"""
import math

import numpy as np

SPEED_OF_LIGHT = 2.99792458e10          # cm s^-1
STEFAN_BOLTZMANN = 5.670374419e-5       # erg cm^-2 s^-1 K^-4
PLANCK = 6.62607015e-27                 # erg s
BOLTZMANN = 1.380649e-16                # erg K^-1
SOLAR_MASS = 1.98847e33                 # g
MEGAPARSEC = 3.0856775814913673e24      # cm
SECONDS_PER_DAY = 86400.0
BETA = 13.4
HEATING_NORMALIZATION = 4.0e18          # erg s^-1 g^-1
HEATING_T0_SECONDS = 1.3
HEATING_SIGMA_SECONDS = 0.11
HEATING_EXPONENT = 1.3

# Barnes et al. 2016, Table 1: (M/Msun, v/c) -> (a, b, d)
BARNES_MASSES = (1e-3, 5e-3, 1e-2, 5e-2)
BARNES_VELOCITIES = (0.1, 0.2, 0.3)
BARNES_TABLE = {
    (1e-3, 0.1): (2.01, 0.28, 1.12), (1e-3, 0.2): (4.52, 0.62, 1.39), (1e-3, 0.3): (8.16, 1.19, 1.52),
    (5e-3, 0.1): (0.81, 0.19, 0.86), (5e-3, 0.2): (1.90, 0.28, 1.21), (5e-3, 0.3): (3.20, 0.45, 1.39),
    (1e-2, 0.1): (0.56, 0.17, 0.74), (1e-2, 0.2): (1.31, 0.21, 1.13), (1e-2, 0.3): (2.19, 0.31, 1.32),
    (5e-2, 0.1): (0.27, 0.10, 0.60), (5e-2, 0.2): (0.55, 0.13, 0.90), (5e-2, 0.3): (0.95, 0.15, 1.13),
}


def time_grid(start_days=1e-4, stop_days=40.0, points=900):
    return np.geomspace(start_days, stop_days, points)


def heating_per_gram(time_days):
    seconds = np.asarray(time_days) * SECONDS_PER_DAY
    bracket = 0.5 - np.arctan((seconds - HEATING_T0_SECONDS) / HEATING_SIGMA_SECONDS) / math.pi
    return HEATING_NORMALIZATION * bracket ** HEATING_EXPONENT


def _bracket(values, value):
    value = min(max(value, values[0]), values[-1])
    for index in range(len(values) - 1):
        if value <= values[index + 1]:
            return index, value
    return len(values) - 2, value


def thermalization_coefficients(mass_solar, velocity_c):
    log_masses = [math.log10(m) for m in BARNES_MASSES]
    mass_index, log_mass = _bracket(log_masses, math.log10(mass_solar))
    velocity_index, velocity = _bracket(BARNES_VELOCITIES, velocity_c)
    m0, m1 = BARNES_MASSES[mass_index], BARNES_MASSES[mass_index + 1]
    v0, v1 = BARNES_VELOCITIES[velocity_index], BARNES_VELOCITIES[velocity_index + 1]
    x = (log_mass - log_masses[mass_index]) / (log_masses[mass_index + 1] - log_masses[mass_index])
    y = (velocity - v0) / (v1 - v0)
    corners = [np.array(BARNES_TABLE[key]) for key in ((m0, v0), (m1, v0), (m0, v1), (m1, v1))]
    return tuple((1 - x) * (1 - y) * corners[0] + x * (1 - y) * corners[1] + (1 - x) * y * corners[2] + x * y * corners[3])


def thermalization_efficiency(time_days, mass_solar, velocity_c):
    a, b, d = thermalization_coefficients(mass_solar, velocity_c)
    t = np.asarray(time_days)
    x = 2.0 * b * t ** d
    return 0.36 * (np.exp(-a * t) + np.log1p(x) / x)


def diffusion_time_days(mass_solar, velocity_c, opacity):
    return math.sqrt(2.0 * opacity * mass_solar * SOLAR_MASS / (BETA * velocity_c * SPEED_OF_LIGHT * SPEED_OF_LIGHT)) / SECONDS_PER_DAY


def deposited_power(time_days, mass_solar, velocity_c, include_thermalization=True):
    power = mass_solar * SOLAR_MASS * heating_per_gram(time_days)
    if include_thermalization:
        power = power * thermalization_efficiency(time_days, mass_solar, velocity_c)
    return power


def arnett_luminosity(time_days, deposited, diffusion_days):
    """L(t) on an increasing grid with an exponential integrator.

    Over each step the deposited power is taken as linear in u = t^2. The
    kernel exp(-(t1^2 - u)/td^2) is then integrated exactly, which stays
    accurate when a step is long compared with td (late times).
    """
    luminosity = np.zeros_like(time_days)
    tau = diffusion_days ** 2
    for index in range(1, len(time_days)):
        t0, t1 = time_days[index - 1], time_days[index]
        q0, q1 = deposited[index - 1], deposited[index]
        x = (t1 * t1 - t0 * t0) / tau
        decay = math.exp(-x)
        # g = (1 - exp(-x)) / x, with a series near x = 0 to avoid cancellation
        g = 1.0 - x / 2.0 + x * x / 6.0 - x ** 3 / 24.0 if x < 1e-4 else -math.expm1(-x) / x
        luminosity[index] = luminosity[index - 1] * decay + q1 - q0 * decay - (q1 - q0) * g
    return luminosity


def photosphere(time_days, luminosity, velocity_c, floor_temperature):
    radius_free = velocity_c * SPEED_OF_LIGHT * time_days * SECONDS_PER_DAY
    with np.errstate(divide='ignore', invalid='ignore'):
        temperature_free = (luminosity / (4.0 * math.pi * STEFAN_BOLTZMANN * radius_free ** 2)) ** 0.25
        receded = temperature_free <= floor_temperature
        temperature = np.where(receded, floor_temperature, temperature_free)
        radius = np.where(receded, np.sqrt(luminosity / (4.0 * math.pi * STEFAN_BOLTZMANN * floor_temperature ** 4)), radius_free)
    return temperature, radius


def component_light_curve(time_days, mass_solar, velocity_c, opacity, floor_temperature, include_thermalization=True):
    deposited = deposited_power(time_days, mass_solar, velocity_c, include_thermalization)
    diffusion = diffusion_time_days(mass_solar, velocity_c, opacity)
    luminosity = arnett_luminosity(time_days, deposited, diffusion)
    temperature, radius = photosphere(time_days, luminosity, velocity_c, floor_temperature)
    return dict(deposited=deposited, luminosity=luminosity, temperature=temperature, radius=radius, diffusion_days=diffusion)


def blackbody_flux_density(frequency_hz, temperature, radius, distance_cm):
    """Observed F_nu (erg s^-1 cm^-2 Hz^-1) of a sphere of radius R at distance D."""
    exponent = PLANCK * frequency_hz / (BOLTZMANN * temperature)
    planck = 2.0 * PLANCK * frequency_hz ** 3 / SPEED_OF_LIGHT ** 2 / np.expm1(np.minimum(exponent, 700.0))
    return math.pi * planck * (radius / distance_cm) ** 2


def ab_magnitude(flux_density):
    with np.errstate(divide='ignore'):
        return -2.5 * np.log10(flux_density) - 48.6


def model_magnitudes(time_days, components, wavelengths_angstrom, distance_mpc):
    """Apparent AB magnitudes (no extinction) at monochromatic effective wavelengths."""
    grid = time_grid()
    curves = [component_light_curve(grid, *component) for component in components]
    distance = distance_mpc * MEGAPARSEC
    magnitudes = {}
    for band, wavelength in wavelengths_angstrom.items():
        frequency = SPEED_OF_LIGHT / (wavelength * 1e-8)
        total = np.zeros_like(grid)
        for curve in curves:
            total = total + blackbody_flux_density(frequency, curve['temperature'], curve['radius'], distance)
        magnitudes[band] = np.interp(np.log(time_days), np.log(grid), ab_magnitude(total))
    return magnitudes, curves, grid
