"""Conditional B1 flight and spherical assembly screen, with a full-network endpoint test."""
import argparse
import hashlib
import json
from pathlib import Path
import sys

import numpy as np
from scipy.constants import epsilon_0
from scipy.optimize import brentq

RELEASE = 1.1e9
DENSITY = 1000.
SHOCK_HEAT = 123.94e9
GRAIN_RADIUS = .01
APERTURE = 100.
OUTLETS = 100_000
HOT_DURATION = 82.27795789289296e-6


def read(path):
    return json.loads(path.read_text())


def write(path, data):
    path.write_text(json.dumps(data, indent=2, allow_nan=False) + '\n')


def flight(trace, draws):
    """Propagate sampled volume-uniform material inside independently perturbed packets."""
    mass = trace['mass_kg']
    rng = np.random.default_rng(18031)
    cells = np.searchsorted(np.cumsum(mass) / mass.sum(), rng.random(draws))
    fraction = rng.random(draws)
    axial = rng.normal(size=(2, draws))
    transverse = rng.normal(size=(2, draws))
    pupil = rng.uniform(size=draws)
    phi = rng.uniform(0, 2*np.pi, draws)
    # Equal-area parallel sectors with the small-angle cap approximation.
    cap = 2 / np.sqrt(OUTLETS)
    sectors = cap * np.sqrt(pupil) * np.array([np.cos(phi), np.sin(phi)])
    r_far = trace['radius_m'][-1]
    v_far = trace['reverse_velocity_m_s'][-1]
    times = trace['time_s']
    anchor_radius = (r_far[cells]**3 + fraction*np.diff(r_far**3)[cells])**(1/3)
    speed = np.interp(anchor_radius, r_far, v_far)
    travel = (RELEASE - anchor_radius) / speed
    flight_weights = np.quantile(travel, [.05, .5, .95])
    outer_for_bulk = (mass.sum() / (4*np.pi/3 * DENSITY))**(1/3)
    bulk_time = np.interp(outer_for_bulk, trace['radius_m'][:, -1], times)
    # Keep the cold tangent ballistic as an independent check. Once the
    # radial average exceeds solid density, interpenetrating grains would
    # be required, so later ballistic densities are diagnostic only.
    cold_bulk_time = times[-1] - (r_far[-1]-outer_for_bulk)/v_far[-1]

    def cold_density(before_hot):
        edges = r_far + v_far*(before_hot-times[-1])
        return mass/(4*np.pi/3*np.diff(edges**3))

    cold_first_dense = brentq(lambda t: max(cold_density(t))-DENSITY,
                              cold_bulk_time, times[-1])
    cold_at_bulk = cold_density(cold_bulk_time)
    cold_diagnostics = dict(bulk_crossing_s=cold_bulk_time, first_local_crossing_s=cold_first_dense,
                            peak_at_bulk_kg_m3=float(max(cold_at_bulk)),
                            mass_above_grain_density_at_bulk=float(mass[cold_at_bulk>DENSITY].sum()/mass.sum()))

    scenarios = {'ideal': (0, 0, 0, 0), 'parallel_aperture': (0, 0, 0, APERTURE)}
    for label, values in (
        ('timing_us', [.1, .3, 1, 3, 10, 30]),
        ('pointing_nrad', [.3, 1, 3, 10, 30, 100]),
        ('speed_ppb', [.3, 1, 3, 10, 30, 100]),
    ):
        for value in values:
            case = [0., 0., 0., 0.]
            case[['timing_us', 'pointing_nrad', 'speed_ppb'].index(label)] = value
            scenarios[f'{label}_{value:g}'] = case
    scenarios['combined_example'] = (1, 3, 3, 0)
    snapshots = {}
    for when in [1000, 100, 10, 1, .01, .001, 1e-4, bulk_time, 0]:
        if when > times[-1]:
            radius = anchor_radius + speed*(when-times[-1])
        else:
            edges = np.array([np.interp(when, times, col) for col in trace['radius_m'].T])
            radius = (edges[cells]**3 + fraction*np.diff(edges**3)[cells])**(1/3)
        released = radius < RELEASE
        released_fraction = float(np.mean(released))
        if not np.all(released):
            snapshots[f'{when:.12g}'] = {'released_mass_fraction': released_fraction}
            continue
        sample = {}
        for label, (jitter, angle, dv, aperture) in scenarios.items():
            dr = speed * jitter*1e-6 * axial[0] + (RELEASE-radius)*dv*1e-9*axial[1]
            dx, dy = transverse * (RELEASE-radius)*angle*1e-9 + sectors * (aperture/cap)
            displaced = np.sqrt((radius+dr)**2 + dx**2 + dy**2)
            # Mass/volume in radial quantile bins, trimming the sparse outermost 0.5%.
            q = np.linspace(0, .995, 200)
            boundaries = np.quantile(displaced, q)
            boundaries[0] = 0.
            rho = mass.sum() * np.diff(q) / (4*np.pi/3 * np.diff(boundaries**3))
            sample[label] = {
                'mass_inside_reference_r99': float(np.mean(displaced <= np.quantile(radius, .99))),
                'mass_radially_averaged_above_1g_cm3': float(np.diff(q)[rho >= DENSITY].sum()),
                'r50_m': float(np.median(displaced)),
                'radial_position_error_rms_m': float(np.sqrt(np.mean((displaced-radius)**2))),
                'position_error_rms_m': float(np.sqrt(np.mean(dr**2 + dx**2 + dy**2))),
            }
        snapshots[f'{when:.12g}'] = sample
    # Isolated sphere on a uniform transverse magnetic field and a cylindrical
    # uncompensated beam, each separately. Speed distribution matters for the former.
    q_over_m_per_V = 3*epsilon_0/(DENSITY*GRAIN_RADIUS**2)
    magnetic = {str(field): float(np.quantile(.5*q_over_m_per_V*field*speed*travel**2, .5))
                for field in [1e-9, 1e-6]}
    current_mass = mass.sum()/(700*OUTLETS)
    v = float(np.sqrt(np.mean(speed**2)))
    line_mass = current_mass/v
    beam_accel_per_V2 = q_over_m_per_V**2*line_mass/(2*np.pi*epsilon_0*APERTURE)
    # A linearized initial-edge displacement, valid for small expansion.
    beam_m_per_V2 = .5*beam_accel_per_V2*(RELEASE/v)**2
    return dict(flight_time_quantiles_s=flight_weights.tolist(), nominal_bulk_crossing_s=bulk_time,
                snapshots=snapshots, cold_tangent=cold_diagnostics, draws=draws, speed_rms_m_s=v,
                magnetic_m_per_V=magnetic, uncompensated_beam_edge_m_per_V2=beam_m_per_V2,
                angular_energy_J_kg=v*v/OUTLETS*(1-2/(3*OUTLETS)))


def remap_radii(edges, velocity, mass, jitter_us, angle_nrad, speed_ppb):
    """Angle-averaged positional broadening, with a finite 3σ error envelope."""
    rng = np.random.default_rng(71013)
    total = 750_000
    cdf = np.r_[0., np.cumsum(mass)/mass.sum()]
    cdf[-1] = 1.
    q = (np.arange(total) + .5)/total
    r = np.interp(q, cdf, edges**3)**(1/3)
    speed = np.interp(r, edges, np.r_[0., velocity])
    errors = np.clip(rng.normal(size=(4, total)), -3, 3)
    delta_r = speed*jitter_us*1e-6*errors[0] + RELEASE*speed_ppb*1e-9*errors[1]
    impact = RELEASE*angle_nrad*1e-9*np.hypot(errors[2], errors[3])
    remapped = np.sqrt((r+delta_r)**2 + impact**2)
    return np.quantile(remapped, cdf[1:])


CASES = {
    'reference-entropy': (None, None),
    'quarter-contact-heat': (SHOCK_HEAT/4, None),
    'full-contact-heat': (SHOCK_HEAT, None),
    'small-arrival-error': (None, (1, 3, 3)),
    'medium-arrival-error': (None, (3, 9, 9)),
    'large-arrival-error': (None, (10, 30, 30)),
}


def radial_cases(trace, root, out, baseline_path, selected_case, burn_duration):
    sys.path[:0] = [str(root), str(root/'b2-completion'), str(root/'mixture-design')]
    import radial_completion as radial
    import pulse_model as pm
    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))
    center = eos.state(1000., 2e8, ye, yi)
    time_unit = 3000/np.sqrt(center.gamma1*center.p/1000.)
    times = trace['time_s']
    mass = trace['mass_kg']
    edges = trace['radius_m']
    radius_bulk = (mass.sum()/(4*np.pi/3*DENSITY))**(1/3)
    duration = float(np.interp(radius_bulk, edges[:, -1], times))

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

    r0 = at_contact('radius_m')
    v0 = at_contact('reverse_velocity_m_s')[1:]
    mnode = .5*(mass + np.r_[mass[1:], 0.])
    rho = mass/(4*np.pi/3*np.diff(r0**3))/1000
    # Deposit an explicit energy budget out of the incoming nodal kinetic
    # inventory. Three closure cases share the energy of the reference precursor.
    reference_T = at_contact('temperature_K')
    energy = float(mass @ (eos.state(rho, reference_T, ye, yi).e * 1e-4)
                   + .5*mnode @ v0**2)
    cold = eos.state(rho, np.full_like(rho, 1e5), ye, yi).e*1e-4

    def run(name, radii, velocities, temperatures, elapsed, nuclear):
        profile = dict(outer_radius_m=radii.tolist(), velocity_m_s=velocities.tolist(),
                       T_K=temperatures.tolist(), description=name)
        write(out/(name+'.initial.json'), profile)
        path = out/(name+'.npz')
        record = radial.simulate('B1', 2e8, 1e6, 30., zones=len(mass), nuclear=nuclear,
                                 radiation=True, kappa=.001, initial_profile=profile,
                                 rtol=1e-7, atol=1e-12, final_time_units=elapsed/time_unit,
                                 art_linear=.5, art_quad=2., viscosity_mode='compression_cap',
                                 save_trace=path, trace_samples=180)
        write(out/(name+'.json'), record)
        data = np.load(path)
        z = data['state'][:, -1].reshape(len(mass), -1)
        return record, (z[:, pm.NN+1]*30, z[:, pm.NN+2]*30/time_unit, z[:, pm.NN]*2e8)

    summary = {}
    if baseline_path:
        baseline = read(baseline_path)
    else:
        baseline, _ = run('prescribed-burn', edges[0, 1:], -trace['reverse_velocity_m_s'][0, 1:],
                          trace['temperature_K'][0], HOT_DURATION, True)

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

    summary = {'prescribed': dict(deposited_J=deposited(baseline), success=baseline['success'])}
    for name, (heat, errors) in CASES.items():
        if selected_case and name != selected_case:
            continue
        T = reference_T if heat is None else np.array([
            brentq(lambda t: eos.state(d, t, ye, yi).e*1e-4-e-heat, 1e5, 3e8)
            for d, e in zip(rho, cold)])
        initial_edges = r0[1:] if errors is None else remap_radii(r0, v0, mass, *errors)
        initial_rho = mass/(4*np.pi/3*np.diff(np.r_[0., initial_edges]**3))/1000
        thermal = float(mass @ (eos.state(initial_rho, T, ye, yi).e*1e-4))
        speed_factor = np.sqrt((energy-thermal)/(.5*mnode @ v0**2))
        prep, endpoint = run(name+'-preparation', initial_edges, -v0*speed_factor, T, duration, False)
        result, _ = run(name+'-burn', *endpoint, burn_duration, True)
        rm, vm, tm = endpoint
        density = mass/(4*np.pi/3*np.diff(np.r_[0., rm]**3))
        retention = deposited(result)/deposited(baseline)
        summary[name] = dict(preparation_success=prep['success'], burn_success=result['success'],
                             deposited_J=deposited(result), retained=retention,
                             meets_90_percent=bool(prep['success'] and result['success'] and retention >= .9),
                             handoff_outer_radius_m=rm[-1], mass_above_1g_cm3=float(mass[density>=1000].sum()/mass.sum()),
                             arrival_errors_us_nrad_ppb=errors, speed_factor=speed_factor,
                             burn_duration_s=burn_duration, preparation_initial_J=prep['initial_energy_J'],
                             prescribed_initial_J=baseline['initial_energy_J'],
                             handoff_initial_J=result['initial_energy_J'],
                             prep_energy_residual=prep['energy_residual_fraction_initial'],
                             burn_energy_residual=result['energy_residual_fraction_initial'])
        write(out/'radial-summary.json', summary)
        print(name, summary[name], flush=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('trace', type=Path)
    parser.add_argument('--research-root', type=Path)
    parser.add_argument('--out', type=Path, default=Path('.'))
    parser.add_argument('--baseline', type=Path)
    parser.add_argument('--case', choices=CASES)
    parser.add_argument('--burn-duration-us', type=float, default=HOT_DURATION*1e6)
    parser.add_argument('--draws', type=int, default=160_000)
    args = parser.parse_args()
    args.out.mkdir(exist_ok=True, parents=True)
    trace = np.load(args.trace)
    results = flight(trace, args.draws)
    results['input_sha256'] = hashlib.sha256(args.trace.read_bytes()).hexdigest()
    write(args.out/'flight.json', results)
    if args.research_root:
        radial_cases(trace, args.research_root.resolve(), args.out, args.baseline, args.case, args.burn_duration_us*1e-6)
