"""Nitrogen-15 correlated launch-error screen at a fixed prepared energy."""
import argparse
import hashlib
from pathlib import Path
import sys

import numpy as np
from scipy.special import ndtri
from scipy.stats import qmc

from assemble import DENSITY, HOT_DURATION, RELEASE, read, write

MODES = ('timing-us', 'speed-ppb', 'loading-percent', 'common-fast-ppb',
         'common-slow-ppb', 'dipole-pointing-nrad',
         'dipole-joint-late-heavy', 'dipole-joint-early-heavy',
         'all-six-late-heavy', 'all-six-early-heavy')


def displaced_edges(edges, speed, mass, mode, amplitude):
    """Spherical mass quantiles of the perturbed angular arrival geometry."""
    cdf = np.r_[0., np.cumsum(mass)/sum(mass)]
    cdf[-1] = 1.
    count = 65_536
    boundaries = np.linspace(0, 1, count+1)**3
    weights = np.diff(boundaries)
    q = boundaries[:-1]+.5*weights
    r = np.interp(np.r_[q, 1.], cdf, edges**3)**(1/3)
    v = np.interp(r, edges, np.r_[0., speed])
    # Keep the central seed delivery separate, tapering the correction over
    # the innermost 20 m of the reference profile at bulk crossing.
    weight = 1-np.exp(-(r/20)**2)
    advance, miss = np.zeros_like(r), np.zeros_like(r)
    joint = mode.startswith('dipole-joint')
    if mode == 'timing-us' or joint:
        advance += v * amplitude*1e-6
    if mode == 'speed-ppb' or joint:
        advance += RELEASE * amplitude*1e-9 * (3 if joint else 1)
    if mode == 'dipole-pointing-nrad' or joint:
        miss += RELEASE * amplitude*1e-9 * (3 if joint else 1)
    # Equal-area latitude quadrature. The signs split the sphere into two
    # coherent hemispheres. Polar pointing has fixed tangential amplitude.
    latitudes = (np.arange(16)+.5)/8-1
    axial = np.sign(latitudes[:, None])*advance
    if mode in ('common-fast-ppb', 'common-slow-ppb'):
        # Remove the global clock shift that minimizes the mass-weighted
        # squared radial error, leaving the error from unequal flight times.
        leverage = np.dot(weights, v[:-1])/np.dot(weights, v[:-1]**2)
        sign = 1 if mode == 'common-fast-ppb' else -1
        axial = np.full((len(latitudes), 1), sign) * (1-v*leverage) * RELEASE*amplitude*1e-9
    polar = mode.startswith('dipole-')
    latitude_factor = np.sqrt(1-latitudes**2)
    transverse = miss*weight
    signed_radius = r - axial*weight
    distance = np.hypot(signed_radius, transverse)
    angular_weights = np.full(len(latitudes), 1./len(latitudes))
    if mode.startswith('dipole-joint'):
        loading_sign = 1 if mode.endswith('early-heavy') else -1
        angular_weights *= 1 + loading_sign*(amplitude/100)*np.sign(latitudes)
    ordered = np.argsort(distance[:, :-1], axis=None)
    w = (angular_weights[:, None]*weights).ravel()[ordered]
    radii = np.interp(cdf[1:], np.cumsum(w)-.5*w, distance[:, :-1].ravel()[ordered])
    radii[-1] = max(radii[-1], distance[:, -1].max())
    if np.any(np.diff(np.r_[0., radii])<=0):
        raise ValueError('unordered remap')
    centroid_z = latitudes[:, None]*signed_radius
    if polar:
        centroid_z -= latitude_factor[:, None]*transverse
    return radii, float(angular_weights @ centroid_z[:, :-1] @ weights)


def budget_edges(edges, speed, mass, mode, amplitude, stress_sampling):
    """Superimpose the independent launch scatter and the coherent dipole."""
    cdf = np.r_[0., np.cumsum(mass)/sum(mass)]
    cdf[-1] = 1.
    u, latitude, *scatter = qmc.Sobol(6, scramble=True, seed=2284).random_base2(20).T
    r = np.interp(u**3, cdf, edges**3)**(1/3)
    v = np.interp(r, edges, np.r_[0., speed])
    mu = 2*latitude-1
    hemisphere = np.sign(mu)
    normal = ndtri(scatter)
    if stress_sampling:
        # Audit the seed assumption and omitted tails together.
        protected = np.ones_like(r)
    else:
        normal = np.clip(normal, -3, 3)
        protected = 1-np.exp(-(r/20)**2)
    timing, speed_error, polar, azimuthal = normal

    axial = amplitude*(v*1e-6*timing + RELEASE*3e-9*speed_error)
    axial += amplitude*hemisphere*protected*(v*.3e-6 + RELEASE*1e-9)
    transverse_polar = amplitude*RELEASE*1e-9*(3*polar + protected)
    transverse_azimuthal = amplitude*RELEASE*3e-9*azimuthal
    signed_radius = r-axial
    distance = np.sqrt(signed_radius**2 + transverse_polar**2 + transverse_azimuthal**2)

    loading_sign = 1 if mode.endswith('early-heavy') else -1
    weight = 3*u*u*(1 + loading_sign*.003*amplitude*hemisphere)
    weight /= weight.sum()
    order = np.argsort(distance)
    sorted_weight = weight[order]
    radii = np.interp(cdf[1:], np.cumsum(sorted_weight)-.5*sorted_weight, distance[order])
    centroid_z = mu*signed_radius - np.sqrt(1-mu*mu)*transverse_polar
    return radii, float(weight @ centroid_z)


def calculate(trace, root, baseline, mode, amplitude, zones, stress_sampling):
    sys.path[:0] = [str(root), str(root/'b2-completion'), str(root/'mixture-design')]
    import pulse_model as pm
    import radial_completion as radial
    import updated_network
    from fast_eos import FastEOS

    y = np.zeros(pm.NN)
    y[pm.SPECIES.index('p')] = 2/17
    y[pm.SPECIES.index('n15')] = 1/17
    _, desired, _ = radial.initial('B1')
    radial.initial = lambda stage: (y.copy(), desired, 1/17)
    updated_network.install(radial, quantile='median')
    eos = FastEOS()
    ye, yi = float(pm.ZZ@y), float(sum(y))
    mass = trace['mass_kg']
    radius_bulk = (mass.sum()/(4*np.pi/3*DENSITY))**(1/3)
    time = trace['time_s']
    duration = float(np.interp(radius_bulk, trace['radius_m'][:, -1], time))

    def at_contact(field):
        return np.array([np.interp(duration, time, x) for x in trace[field].T])

    edges = at_contact('radius_m')
    speed = at_contact('reverse_velocity_m_s')[1:]
    temp = at_contact('temperature_K')
    original_zones = len(mass)
    if zones != original_zones:
        # The radial solver fixes enclosed mass at (i/zones)^3. Refining
        # volume linearly in mass preserves each source cell's mean density.
        old_mass_fraction = np.r_[0., np.cumsum(mass)/sum(mass)]
        old_mass_fraction[-1] = 1.
        new_mass_fraction = np.linspace(0, 1, zones+1)**3
        new_mass = np.diff(new_mass_fraction)*sum(mass)
        new_edges = np.interp(new_mass_fraction, old_mass_fraction, edges**3)**(1/3)
        speed = np.interp(new_edges[1:], edges, np.r_[0., speed])
        integrated_temperature = np.interp(new_mass_fraction, old_mass_fraction, np.r_[0., np.cumsum(mass*temp)])
        temp = np.diff(integrated_temperature)/new_mass
        mass, edges = new_mass, new_edges
    nodes = .5*(mass + np.r_[mass[1:], 0.])
    nominal_ke = .5*nodes @ speed**2

    def thermal(radii, factor):
        rho = mass*factor/(4*np.pi/3*np.diff(np.r_[0., radii]**3))/1000
        return float((mass*factor) @ eos.state(rho, temp, ye, yi).e * 1e-4)

    reference_energy = thermal(edges[1:], 1) + nominal_ke
    factors = [1-amplitude/100, 1+amplitude/100] if mode == 'loading-percent' else [1.]
    if mode == 'loading-percent':
        radii = edges[1:]
        cell_centers = ((edges[1:]**3+edges[:-1]**3)/2)**(1/3)
        centroid = float(.5 * amplitude/100 * (mass @ cell_centers)/mass.sum())
    elif amplitude == 0:
        radii, centroid = edges[1:], 0.
    elif mode.startswith('all-six'):
        radii, centroid = budget_edges(edges, speed, mass, mode, amplitude, stress_sampling)
    else:
        radii, centroid = displaced_edges(edges, speed, mass, mode, amplitude)
    if np.any(np.diff(np.r_[0., radii])<=0):
        raise ValueError('unordered remap')
    mean_thermal = np.mean([thermal(radii, factor) for factor in factors])
    speed_scale = float(np.sqrt((reference_energy-mean_thermal)/nominal_ke))

    def simulate(profile, factor, elapsed, nuclear):
        density = 1000*factor
        center = eos.state(density, 2e8, ye, yi)
        unit = 3000/np.sqrt(center.gamma1*center.p/density)
        result = radial.simulate('B1', 2e8, density*1000, 30., zones=len(mass), nuclear=nuclear,
                                 radiation=True, kappa=.001, initial_profile=profile,
                                 rtol=1e-7, atol=1e-12, final_time_units=elapsed/unit,
                                 art_linear=.5, art_quad=2., viscosity_mode='compression_cap')
        assert result['success'] and result['termination_reason'] == 'final_time', result['message']
        assert abs(result['elapsed_s']-elapsed)<1e-12
        assert abs(result['energy_residual_fraction_initial'])<1e-5
        assert result['max_cell_baryon_residual']<1e-10
        return result

    def deposit(record):
        return record['nuclear_energy_J'] - record['weak_energy_escaped_upper_J']

    initial = dict(outer_radius_m=radii.tolist(), velocity_m_s=(-speed*speed_scale).tolist(),
                   T_K=temp.tolist(), description=f'{mode} {amplitude:g} at bulk crossing')
    sectors = []
    for factor in factors:
        prep = simulate(initial, factor, duration, False)
        burn = simulate(prep['profile'], factor, HOT_DURATION, True)
        assert abs((prep['initial_energy_J']-prep['radiation_escaped_J'])/burn['initial_energy_J']-1)<1e-8
        sectors.append(dict(density_factor=factor, prep=prep, burn=burn))
    assert abs(np.mean([s['prep']['initial_energy_J'] for s in sectors])/reference_energy-1)<1e-8
    retained = float(np.mean([deposit(s['burn']) for s in sectors])/deposit(baseline))
    return dict(mode=mode, amplitude=amplitude, retained=retained, passes=retained>=.9,
                published_reference_J=deposit(baseline), mean_preparation_energy_J=reference_energy,
                zones=zones, stress_sampling=stress_sampling, speed_scale=speed_scale, initial_centroid_z_m=centroid,
                bulk_crossing_profile=initial, sectors=sectors)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('trace', type=Path)
    parser.add_argument('--research-root', type=Path, required=True)
    parser.add_argument('--baseline', type=Path, required=True)
    parser.add_argument('--mode', choices=MODES, required=True)
    parser.add_argument('--amplitude', type=float, required=True)
    parser.add_argument('--zones', type=int, choices=(64, 128, 256), default=128)
    parser.add_argument('--stress-sampling', action='store_true', help='Use unclipped Gaussian errors and no coherent seed taper')
    parser.add_argument('--out', type=Path, required=True)
    args = parser.parse_args()
    if not np.isfinite(args.amplitude) or args.amplitude < 0 or (
            (args.mode == 'loading-percent' or args.mode.startswith(('dipole-joint', 'all-six'))) and args.amplitude >= 100):
        parser.error('amplitude must be finite and nonnegative; loading must be below 100%')
    if args.stress_sampling and not args.mode.startswith('all-six'):
        parser.error('--stress-sampling requires an all-six case')
    try:
        with np.load(args.trace) as trace:
            result = calculate(trace, args.research_root, read(args.baseline), args.mode, args.amplitude, args.zones, args.stress_sampling)
    except ValueError as exc:
        if str(exc).startswith('EOS table exceeded'):
            reason = 'Projected density exceeded the EOS table'
        elif str(exc) == 'unordered remap':
            reason = 'Projected shell boundaries overlapped'
        else:
            raise
        result = dict(mode=args.mode, amplitude=args.amplitude, status='model-range exit', detail=reason)
    result['input_sha256'] = hashlib.sha256(args.trace.read_bytes()).hexdigest()
    args.out.parent.mkdir(parents=True, exist_ok=True)
    write(args.out, result)
    print(result['mode'], result['amplitude'], result.get('retained', result.get('status')))
