#!/usr/bin/env python3
"""Reproduce all eleven page figures from the published data.

Requires Python 3.10+, NumPy, SciPy and Matplotlib. Run from any directory:
    python code/build_plots.py
The package root contains code/, data/ and (created automatically) plots/.
Original hydro/source scripts are separate inspection snapshots; this reducer
uses only the archived EOS table, endpoint records and raw saved trajectories.
It performs no new hydrodynamic integration or physical validation.
"""
from pathlib import Path
import csv
import hashlib
import json
import re
import sys

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from fast_eos import FastEOS, ARAD_CGS

ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / 'data'
PLOTS = ROOT / 'plots'
COLORS = {'n14': '#3155a3', 'n15': '#c45731', 'c12': '#16816d', 'c13': '#8a4e9e'}
LABELS = {'n14': 'Nitrogen-14', 'n15': 'Nitrogen-15', 'c12': 'Carbon-12', 'c13': 'Carbon-13'}
SPECIES = ['n', 'p', 'he4', 'c12', 'c13', 'n13', 'n14', 'n15', 'o14', 'o15', 'o16',
           'o17', 'o18', 'f17', 'f18', 'f19', 'ne18', 'ne19', 'ne20', 'ne21', 'ne22',
           'na21', 'na22', 'na23', 'mg22', 'mg23', 'mg24']
A = np.array([1 if s in ('n', 'p') else int(re.search(r'\d+', s)[0]) for s in SPECIES])
CHARGE = {'p': 1, 'he': 2, 'c': 6, 'n': 7, 'o': 8, 'f': 9, 'ne': 10, 'na': 11, 'mg': 12}
Z = np.array([0 if s == 'n' else CHARGE[re.sub(r'\d+', '', s)] for s in SPECIES])


def read_json(name):
    return json.loads((DATA / name).read_text())


def verify_inputs():
    manifest = read_json('input-manifest.json')
    for name, expected in manifest['sha256'].items():
        path = ROOT / name
        if not path.is_file():
            raise FileNotFoundError(f'Missing {path}; download the named input before running.')
        actual = hashlib.sha256(path.read_bytes()).hexdigest()
        if actual != expected:
            raise ValueError(f'Input hash mismatch: {name}')
    stage_map = read_json('stage-map.json')['stage_map']
    for key, entry in stage_map.items():
        for suffix, field in [('.npz', 'raw_trace_sha256'), ('.json', 'result_sha256'),
                              ('.initial.json', 'initial_profile_sha256'), ('.inputs.json', 'input_record_sha256')]:
            actual = hashlib.sha256((DATA / f'{key}{suffix}').read_bytes()).hexdigest()
            if actual != entry[field]:
                raise ValueError(f'Original research stage-map mismatch: {key}{suffix}')
    provenance = read_json('mixture-gain-provenance.json')
    if hashlib.sha256((DATA/'mixture-gain.csv').read_bytes()).hexdigest() != provenance['csv_sha256']:
        raise ValueError('Mixture CSV does not match original plot provenance')
    return manifest


def reduce_trace(key, eos):
    d = read_json(f'{key}.json')
    initial = read_json(f'{key}.initial.json')
    inp = read_json(f'{key}.inputs.json')
    if not d['success'] or d['termination_reason'] != 'final_time':
        raise ValueError(f'{key}: incomplete simulation')
    with np.load(DATA / f'{key}.npz', allow_pickle=False) as z:
        time = z['time_s']; mass = z['cell_mass_kg']; names = z['species'].tolist()
        nz = int(z['zones']); nn = len(names); nv = int(z['variables_per_zone'])
        if names != SPECIES or nz != d['zones'] or nv != nn + 7:
            raise ValueError(f'{key}: unexpected state layout')
        raw = z['state'].reshape(nz, nv, len(time)).transpose(2, 0, 1)
        assert np.isfinite(raw).all() and np.all(np.diff(time) > 0) and time[0] == 0
        np.testing.assert_allclose(time[-1], inp.get('duration_s', inp.get('physical_duration_s')), rtol=1e-12)
        np.testing.assert_allclose(time[-1], d['elapsed_s'], rtol=1e-12)
        np.testing.assert_allclose(mass.sum(), d['mass_kg'], rtol=1e-12)
        y = raw[:, :, :nn]; w = mass / mass.sum()
        radius = raw[:, :, nn+1] * d['R0_m']
        velocity = raw[:, :, nn+2] * float(z['velocity_unit_cm_s']) / 100
        temperature = raw[:, :, nn] * d['T0_K']
        inner = np.column_stack([np.zeros(len(time)), radius[:, :-1]])
        volume = 4*np.pi/3*(radius**3-inner**3)
        assert np.all(volume > 0)
        density = mass[None, :] / volume
        factor = float(z['energy_unit_erg_g']) * 1e-4
        weak = raw[:, :, nn+3] @ mass * factor
        escaped = raw[:, :, nn+4] @ mass * factor
        nuclear = raw[:, :, nn+5] @ mass * factor
    # Match the archived hydro EOS's clipped, baryon-normalized composition.
    clipped = np.maximum(y, 0); norm = clipped @ A
    ye = (clipped @ Z) / norm; yi = clipped.sum(axis=2) / norm
    state = eos.state(density/1000, temperature, ye, yi)
    pressure = state.p * .1
    radiation_pressure = ARAD_CGS * .1 * temperature**4 / 3
    internal = state.e @ mass * 1e-4
    node_mass = np.r_[.5*(mass[:-1]+mass[1:]), .5*mass[-1]]
    kinetic = .5*(velocity**2) @ node_mass
    e0 = d['initial_energy_J']
    residual = (kinetic + internal + escaped + weak - e0 - nuclear) / e0
    mean_y = np.einsum('z,tzn->tn', w, y)
    catalyst0 = mean_y[0, names.index(key)]
    np.testing.assert_allclose(radius[0], initial['outer_radius_m'], rtol=1e-12)
    np.testing.assert_allclose(temperature[0], initial['T_K'], rtol=1e-12)
    np.testing.assert_allclose(velocity[0], initial['velocity_m_s'], rtol=1e-12)
    np.testing.assert_allclose(y[0], np.tile([inp['initial_Y'].get(n, 0) for n in names], (nz, 1)), atol=1e-14)
    np.testing.assert_allclose(mean_y[-1]*A, [d['output_mass_fractions'][n] for n in names], atol=1e-12)
    np.testing.assert_allclose(kinetic[0]+internal[0], e0, rtol=1e-12)
    np.testing.assert_allclose(kinetic[-1], d['final_kinetic_J'], rtol=1e-12)
    np.testing.assert_allclose(internal[-1], d['final_internal_J'], rtol=1e-12)
    np.testing.assert_allclose(escaped[-1], d['radiation_escaped_J'], rtol=1e-12)
    np.testing.assert_allclose(weak[-1], d['weak_energy_escaped_upper_J'], rtol=1e-12)
    np.testing.assert_allclose(nuclear[-1], d['integrated_nuclear_energy_J'], rtol=1e-12)
    # Metadata's nuclear energy uses endpoint rest-mass changes; compare separately.
    np.testing.assert_allclose((nuclear[-1]-weak[-1])/e0, d['deposited_nuclear_over_initial_energy'], atol=1e-8)
    np.testing.assert_allclose(residual[-1], d['energy_residual_fraction_initial'], atol=1e-8)
    mass_edges = np.r_[0, np.cumsum(w)]
    j = np.searchsorted(mass_edges, .5)-1; f = (.5-mass_edges[j])/w[j]
    rhalf = np.cbrt(inner[:, j]**3 + f*(radius[:, j]**3-inner[:, j]**3))
    tau = (d['opacity_m2_kg']*density*(radius-inner)).sum(axis=1)
    pmean = pressure @ w; p_rad_mean = radiation_pressure @ w
    ip = int(np.argmax(pmean))
    hist = dict(time_us=time*1e6, rhalf=rhalf, surface=radius[:, -1], rho=density@w,
                temp=temperature@w/1e9, tempmax=temperature.max(axis=1)/1e9,
                gain=(nuclear-weak)/e0, kinetic=kinetic/e0, internal=internal/e0,
                escaped=escaped/e0, weak=weak/e0, residual=residual,
                radiation_fraction=p_rad_mean/pmean, tau=tau,
                isotope={s: mean_y[:, names.index(s)]/catalyst0 for s in ['p','c12','c13','n13','n14','n15','o14','o15','he4']},
                mass_fraction=np.cumsum(w), initial_density=density[0],
                initial_temperature=temperature[0], initial_velocity=velocity[0])
    summary = dict(max_abs_energy_residual_over_input=float(abs(residual).max()),
                   endpoint_residual_over_input=float(residual[-1]),
                   max_cell_baryon_residual=float(abs(y@A-1).max()),
                   initial_surface_radius_m=float(radius[0,-1]),
                   initial_mass_mean_density_kg_m3=float(density[0]@w),
                   initial_mass_mean_temperature_K=float(temperature[0]@w),
                   initial_max_inward_speed_m_s=float(-velocity[0].min()),
                   initial_kinetic_fraction=float(kinetic[0]/e0),
                   radiation_pressure_fraction_at_peak_mass_mean_pressure=float(p_rad_mean[ip]/pmean[ip]),
                   time_peak_mass_mean_pressure_us=float(time[ip]*1e6),
                   photon_escape_over_initial_plus_deposited=float(escaped[-1]/(e0+nuclear[-1]-weak[-1])),
                   min_temperature_K=float(temperature.min()), max_sampled_temperature_K=float(temperature.max()),
                   max_abs_velocity_over_c=float(abs(velocity).max()/299792458),
                   eos_rhoYe_g_cm3_range=[float((density/1000*ye).min()),float((density/1000*ye).max())])
    columns = {name: hist[field] for name, field in [('time_us','time_us'),('half_mass_radius_m','rhalf'),('surface_radius_m','surface'),('mass_mean_density_kg_m3','rho'),('mass_mean_temperature_GK','temp'),('max_cell_temperature_GK','tempmax'),('deposited_nuclear_over_initial_energy','gain'),('kinetic_over_initial','kinetic'),('internal_over_initial','internal'),('photon_escape_over_initial','escaped'),('weak_escape_over_initial','weak'),('energy_residual_over_initial','residual'),('radiation_pressure_fraction_mass_mean','radiation_fraction'),('grey_radial_optical_depth','tau')]}
    columns.update({f'{s}_nuclei_per_initial_catalyst': values for s, values in hist['isotope'].items()})
    with (DATA/f'{key}-history.csv').open('w', newline='') as out:
        writer = csv.writer(out, lineterminator='\n');writer.writerow(columns)
        writer.writerows(zip(*columns.values()))
    return hist, summary


def save(fig, name):
    fig.tight_layout(); fig.savefig(PLOTS/f'{name}.png', bbox_inches='tight', dpi=170);plt.close(fig)


def plot_all(hist):
    plt.rcParams.update({'font.size': 11, 'axes.spines.top': False, 'axes.spines.right': False,
                         'figure.facecolor': 'white', 'axes.grid': True, 'grid.alpha': .18})
    for name, field, ylabel, title, scale in [('radius','rhalf','Half-mass radius (m)','Spherical convergence and rebound','linear'),('density','rho','Mass-weighted density (kg/m³)','Density history','log'),('temperature','temp','Mass-weighted temperature (GK)','Temperature history','linear'),('nuclear','gain','Deposited nuclear / initial hot-pulse energy','Cumulative nuclear energy deposited','linear')]:
        fig, ax = plt.subplots(figsize=(8,4.6))
        for k,h in hist.items(): ax.plot(h['time_us'], h[field], color=COLORS[k], label=LABELS[k], lw=2)
        ax.set(title=title, ylabel=ylabel, yscale=scale, xlabel='Time from prescribed hot start (µs)')
        ax.legend(frameon=False, ncol=2, fontsize=9);save(fig,name)
    fig, axs = plt.subplots(2,2,figsize=(10,7))
    chosen={'n14':['n14','o15'],'n15':['n15','c12','he4'],'c12':['c12','n13','o14'],'c13':['c13','n14','o15']}
    for ax,(k,seq) in zip(axs.flat,chosen.items()):
        h=hist[k]
        for s,style in zip(seq,['-','--',':']): ax.plot(h['time_us'],h['isotope'][s],style,label=s.upper(),lw=2)
        ax.set(title=LABELS[k],xlabel='Time (µs)',ylabel='Nuclei / initial catalyst');ax.legend(frameon=False,fontsize=9)
    fig.suptitle('Principal isotope inventories before cold decay',fontsize=14);save(fig,'isotopes')
    mesh=read_json('mesh-comparison.json')['rows']
    for row in mesh:
        record=read_json(row['record']); assert record['success'] and record['termination_reason']=='final_time'
        np.testing.assert_allclose(record['deposited_nuclear_over_initial_energy'],row['gain'],rtol=1e-12)
    fig,ax=plt.subplots(figsize=(8,4.5));ax.plot([r['zones'] for r in mesh],[r['gain'] for r in mesh],'-o',color=COLORS['n14'],lw=2)
    ax.set(xlabel='Radial zones',ylabel='Deposited nuclear / initial energy',title='Related C12 H/C = 2 profile: mesh comparison',xticks=[64,128,256]);save(fig,'mesh')
    with (DATA/'mixture-gain.csv').open() as f: rows=list(csv.DictReader(f))
    fig,axs=plt.subplots(2,2,figsize=(10,7.5))
    series=[('frozen64_equal_energy','64 zones, frozen rates','#a5adb8','-'),('frozen64_fixed_flow','64 zones, fixed flow','#c4752f','--'),('median_carbon128_equal_energy','128 zones, updated carbon',COLORS['n14'],'-')]
    for ax,stage in zip(axs.flat,['A','B1','B2','C13']):
        for name,label,color,style in series:
            data=sorted([r for r in rows if r['stage']==stage and r['series']==name],key=lambda r:float(r['H_per_catalyst']))
            ax.plot([float(r['H_per_catalyst']) for r in data],[float(r['gain']) for r in data],style,marker='o',ms=3,color=color,label=label)
        ax.set(title=LABELS[dict(zip(['A','B1','B2','C13'],COLORS))[stage]],xlabel='Hydrogen nuclei / catalyst nucleus',ylabel='Deposited nuclear / initial energy')
    axs[0,0].legend(fontsize=8,frameon=False);fig.suptitle('Composition sensitivity at different constraints and resolutions');save(fig,'mixture-gain')
    with (DATA/'plant-tradeoffs.csv').open() as f: rows=list(csv.DictReader(f))
    fig,axs=plt.subplots(1,2,figsize=(11,4.5))
    for label,color in zip(dict.fromkeys(r['series'] for r in rows if r['series']!='Service allocation sensitivity'),[COLORS['n14'],COLORS['n15'],'#707980']):
        data=sorted([r for r in rows if r['series']==label],key=lambda r:float(r['receiver_kg_m2']))
        axs[0].plot([float(r['receiver_kg_m2']) for r in data],[float(r['net_mW_kg']) for r in data],'-o',color=color,ms=4,label=label)
    axs[0].set(xscale='log',xlabel='Hot graphite receiver (kg/m²)',ylabel='Net specific power (mW/kg)',title='Receiver scenarios');axs[0].legend(fontsize=7,frameon=False)
    data=[r for r in rows if r['series']=='Service allocation sensitivity']
    axs[1].plot([float(r['service_kg_m2']) for r in data],[float(r['net_mW_kg']) for r in data],'-o',color=COLORS['n14'])
    axs[1].set(xlabel='General service allocation (kg/m²)',ylabel='Net specific power (mW/kg)',title='Equipment allowance at 350 kg/m² receiver')
    fig.suptitle('Allocated reference before catcher-interface additions');save(fig,'plant-tradeoffs')
    fig,axs=plt.subplots(1,3,figsize=(12,4))
    for k,h in hist.items():
        for ax,field in zip(axs,['initial_density','initial_temperature','initial_velocity']):
            divisor={'initial_density':1,'initial_temperature':1e6,'initial_velocity':1e6}[field]
            ax.plot(h['mass_fraction'],h[field]/divisor,color=COLORS[k],label=LABELS[k],lw=1.8)
    for ax,title,unit in zip(axs,['Density','Temperature','Boundary velocity'],['kg/m³','MK','million m/s']):ax.set(xlabel='Enclosed mass fraction',ylabel=unit,title=title)
    axs[0].set_yscale('log');axs[0].legend(fontsize=8,frameon=False);fig.suptitle('Prescribed initial hot inflow profiles');save(fig,'initial-profiles')
    fig,axs=plt.subplots(2,2,figsize=(10,7))
    for ax,(k,h) in zip(axs.flat,hist.items()):
        for field,label,style in [('kinetic','Kinetic','-'),('internal','Internal','--'),('escaped','Escaped photons',':'),('gain','Nuclear deposited','-.')]:ax.plot(h['time_us'],h[field],style,label=label,lw=1.8)
        ax.set(title=LABELS[k],xlabel='Time (µs)',ylabel='Energy / initial hot-pulse energy')
    axs[0,0].legend(fontsize=8,frameon=False);fig.suptitle('Energy inventory: nuclear deposition becomes internal, kinetic and escaped energy');save(fig,'energy-budget')
    fig,axs=plt.subplots(1,2,figsize=(11,4))
    for k,h in hist.items():
        axs[0].plot(h['time_us'],h['radiation_fraction'],color=COLORS[k],label=LABELS[k])
        axs[1].plot(h['time_us'],h['residual']*1e6,color=COLORS[k])
    axs[0].set(xlabel='Time (µs)',ylabel='Mass-mean radiation P / mass-mean total P',title='Imposed LTE radiation contribution',ylim=(0,1));axs[0].legend(fontsize=8,frameon=False)
    axs[1].set(xlabel='Time (µs)',ylabel='Energy residual / input (parts per million)',title='Saved-state energy closure');save(fig,'radiation-closure')


def main():
    manifest=verify_inputs();PLOTS.mkdir(exist_ok=True)
    eos=FastEOS();hist={};summary={}
    for key in COLORS:hist[key],summary[key]=reduce_trace(key,eos)
    plot_all(hist)
    audit={'scope':'Reconstruction on saved trajectories using their original EOS. Checks numerical consistency; establishes no physical or experimental validation.',
           'inputs_manifest_sha256':hashlib.sha256((DATA/'input-manifest.json').read_bytes()).hexdigest(),
           'reducer_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
           'eos_domain':{'rhoYe_g_cm3':np.exp(eos.ld[[0,-1]]).tolist(),'temperature_K':np.exp(eos.lt[[0,-1]]).tolist()},
           'cases':summary,'runtime':{'python':sys.version.split()[0],'numpy':np.__version__,'matplotlib':matplotlib.__version__},
           'outputs_sha256':{str(p.relative_to(ROOT)):hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(PLOTS.glob('*.png'))}}
    (DATA/'audit-results.json').write_text(json.dumps(audit,indent=2)+'\n')
    print(f'Checked {len(manifest["sha256"])} input hashes, four trace/endpoint/profile accounts; generated eleven figures.')


if __name__=='__main__':main()
