"""Thin-shell patch model of a GRB afterglow (standard library only).

Same physics as the Lab engine, written separately in Python for the tutorial:
- each patch of the jet is a piece of a spherical adiabatic blast wave with the local E_iso(theta)
  (Huang, Dai & Lu 1999 energy equation, initial Lorentz factor 300, no lateral spreading);
- forward-shock synchrotron with the Sari, Piran & Narayan (1998) broken power law, no self-absorption;
- observed flux of a patch: delta^3 N P'_max S(nu / delta) / (4 pi d_L^2), redshift neglected.
Units: cgs, times in days, flux densities in microjansky.
"""
import math

C = 2.99792458e10
M_P = 1.67262192e-24
M_E = 9.1093837e-28
Q_E = 4.80320471e-10
SIGMA_T = 6.6524587e-25
DAY = 86400.0
MPC = 3.0856776e24
MICROJANSKY = 1e-29
D_L = 40 * MPC
GAMMA_0 = 300.0


def gamma_from_swept_mass(x, y):
    """Gamma and Gamma-1 from x = m c^2 / E and y = M_ej c^2 / E (Huang et al. 1999, eq. 10 solved for Gamma)."""
    root = math.sqrt(y * y + 4 * x * (1 + y + x))
    gamma = 2 * (1 + y + x) / (y + root)
    gamma_minus_one = 4 * (1 + y + x) / ((2 + y + 2 * x + root) * (y + root))
    return gamma, gamma_minus_one


def _segment(f0, f1, dlog):
    if f0 <= 0 or f1 <= 0:
        return 0.5 * (f0 + f1) * dlog
    s = math.log(f1 / f0) / dlog
    return f0 * dlog if abs(s) < 1e-9 else (f1 - f0) / s


def track_blast_wave(e_iso, n, t_max_s, growth=1.06, max_steps=760):
    """Radius grid with Gamma-1, t_lab - R/c and comoving time; stops once t_lab - R/c > 1.05 t_max."""
    mass = e_iso / C ** 2
    y = 1 / (GAMMA_0 - 1)
    k = 4 * math.pi / 3 * n * M_P
    r_dec = (y * mass / (k * GAMMA_0)) ** (1 / 3)
    r = 1e-3 * r_dec
    dlog = math.log(growth)
    out = []
    prev = None
    for _ in range(max_steps):
        g, gm1 = gamma_from_swept_mass(k * r ** 3 / mass, y)
        beta = math.sqrt(gm1 * (g + 1)) / g
        omb = 1 / (g * g * (1 + beta))
        lag_f = r * omb / (beta * C)
        prop_f = r / (g * beta * C)
        if prev is None:
            lag, prop = lag_f, prop_f
        else:
            lag = prev[3] + _segment(prev[5], lag_f, dlog)
            prop = prev[4] + _segment(prev[6], prop_f, dlog)
        prev = (r, g, gm1, lag, prop, lag_f, prop_f)
        out.append(prev[:5])
        if lag > 1.05 * t_max_s:
            break
        r *= growth
    return out


def spectrum_shape(nu, nu_m, nu_c, p):
    if nu_m <= nu_c:
        if nu < nu_m:
            return (nu / nu_m) ** (1 / 3)
        if nu < nu_c:
            return (nu / nu_m) ** (-(p - 1) / 2)
        return (nu_c / nu_m) ** (-(p - 1) / 2) * (nu / nu_c) ** (-p / 2)
    if nu < nu_c:
        return (nu / nu_c) ** (1 / 3)
    if nu < nu_m:
        return (nu / nu_c) ** -0.5
    return (nu_m / nu_c) ** -0.5 * (nu / nu_m) ** (-p / 2)


def energy_profile(kind, e_core, theta_c):
    if kind == "top-hat":
        return theta_c, (lambda th: e_core)
    if kind == "spherical":
        return math.pi / 2, (lambda th: e_core)
    width = min(math.pi / 2, 8 * theta_c)
    return width, (lambda th: e_core * math.exp(-0.5 * (th / theta_c) ** 2))


def light_curves(kind, theta_obs, theta_c, log_e, log_n, log_eps_b, log_eps_e, p, days, frequencies,
                 rings=40, azimuths=16, counter_jet=True):
    """Flux density (microjansky) at each (frequency, day). `days` must be sorted ascending."""
    n, eps_b, eps_e = 10 ** log_n, 10 ** log_eps_b, 10 ** log_eps_e
    width, e_of = energy_profile(kind, 10 ** log_e, theta_c)
    t_s = [d * DAY for d in days]
    flux = [[0.0] * len(days) for _ in frequencies]
    scale = 1 / (4 * math.pi * D_L ** 2 * MICROJANSKY)
    dth = width / rings
    dphi = math.pi / azimuths
    cos_v, sin_v = math.cos(theta_obs), math.sin(theta_obs)
    gamma_m_factor = eps_e * (p - 2) / (p - 1) * M_P / M_E
    for i in range(rings):
        lo, hi = i * dth, (i + 1) * dth
        th = 0.5 * (lo + hi)
        e_iso = e_of(th)
        if e_iso <= 0:
            continue
        cell = 2 * math.pi * (math.cos(lo) - math.cos(hi)) / azimuths
        track = track_blast_wave(e_iso, n, t_s[-1])
        ct, st = math.cos(th), math.sin(th)
        mus = []
        for j in range(azimuths):
            cp = math.cos((j + 0.5) * dphi)
            mus.append(ct * cos_v + st * sin_v * cp)
            if counter_jet:
                mus.append(-ct * cos_v + st * sin_v * cp)
        for mu in mus:
            omm = 1 - mu
            arrival = [row[3] + row[0] * omm / C for row in track]
            step = 0
            last = len(track) - 2
            for k, target in enumerate(t_s):
                if target < arrival[0]:
                    continue
                while step < last and arrival[step + 1] < target:
                    step += 1
                a0, a1 = arrival[step], arrival[step + 1]
                if target > a1:
                    break
                f = math.log(target / a0) / math.log(a1 / a0)
                r0, r1 = track[step], track[step + 1]
                r = r0[0] * (r1[0] / r0[0]) ** f
                gm1 = r0[2] * (r1[2] / r0[2]) ** f
                tp = r0[4] * (r1[4] / r0[4]) ** f
                g = 1 + gm1
                beta = math.sqrt(gm1 * (g + 1)) / g
                delta = 1 / (g * (1 - beta * mu))
                e_int = 4 * g * gm1 * n * M_P * C ** 2
                b = math.sqrt(8 * math.pi * eps_b * e_int)
                gyro = Q_E * b / (2 * math.pi * M_E * C)
                gam_m = max(1.0, gamma_m_factor * gm1)
                gam_c = max(1.0, 6 * math.pi * M_E * C / (SIGMA_T * b * b * tp))
                peak = delta ** 3 * (n * r ** 3 * cell / 3) * (M_E * C ** 2 * SIGMA_T * b / (3 * Q_E)) * scale
                nu_m, nu_c = delta * gam_m ** 2 * gyro, delta * gam_c ** 2 * gyro
                for q, nu in enumerate(frequencies):
                    flux[q][k] += peak * spectrum_shape(nu, nu_m, nu_c, p)
    return flux
