"""Evaluate a B1 launcher simulation budget and a metrology record."""
import argparse
import json
from math import isclose, isfinite
from pathlib import Path


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


def valid_number(value):
    return isinstance(value, (int,float)) and not isinstance(value,bool) and isfinite(value)


def metrics(args):
    return dict(timing_rms_us=args['jitter_timing'],
                timing_hemisphere_us=abs(args['coherent_timing']),
                pointing_rms_nrad_per_axis=args['jitter_pointing'],
                pointing_polar_dipole_nrad=abs(args['pointing']),
                speed_rms_ppb=args['jitter_speed'],
                speed_hemisphere_ppb=abs(args['coherent_speed']),
                loading_rms_percent_per_group=args['jitter_loading'],
                loading_hemisphere_percent=abs(args['coherent_loading']),
                charge_rms_V=args['jitter_charge'],
                charge_coherent_V=abs(args['coherent_charge']))


def scenario(name, record, config, full_budget):
    ref=config['reference_deposited_J']
    history=record['history']
    final=history[-1]
    cutoff=final['time_us']-config['terminal_window_us']
    preceding=next(x for x in reversed(history) if x['time_us']<=cutoff)
    drift=(max(x['deposited_J'] for x in history if x['time_us']>=preceding['time_us'])-
           min(x['deposited_J'] for x in history if x['time_us']>=preceding['time_us']))/ref
    shape=record['args']
    tested=metrics(shape) if full_budget else None
    # Earlier runners use the same zero-error defaults for later switches.
    actual={'independent_groups':0,'coherent_timing':0.,'coherent_speed':0.,
            'coherent_loading':0.,'jitter_loading':0.,'loading_phase_correlation':0.,
            'jitter_charge':0.,'coherent_charge':0.,'electric_v_m':0.,'magnetic_ut':0.,**shape}
    if shape.get('profile'):
        actual['profile']=Path(shape['profile']).name
    declared_case=all(key in actual and actual[key]==value
                      for key,value in config['case_inputs'][name].items())
    provenance=(Path(shape['trace']).name==config['trace_name'] and
                all(record['network'].get(k)==v for k,v in config['rate_table'].items()))
    same_budget=not full_budget or all(
        isclose(tested[k],limit,rel_tol=1e-12) for k,limit in config['limits'].items())
    complete=(isclose(final['time_us'],shape['duration'],abs_tol=1e-8)
              and final['deposited_J']==record['deposited_J'])
    energy=abs(record['energy_residual_J'])/max(ref,record['initial_energy_J'])
    composition=record['mass_fraction_closure_max']
    closure=max(energy,composition)<=config['maximum_ledger_residual_fraction']
    yield_fraction=record['deposited_J']/ref
    return dict(yield_fraction=yield_fraction,plateau_change_fraction=drift,complete=complete,
                through_us=final['time_us'],ledger_pass=closure,same_budget=same_budget,
                pass_yield=yield_fraction>=config['required_yield_fraction'],
                declared_case=declared_case,provenance_pass=provenance,
                pass_diagnostics=complete and closure and same_budget and declared_case and provenance and
                    drift<=config['terminal_yield_change_max'])


def assess(config, records, metrology=None):
    threshold=config['required_yield_fraction']
    nominal={name:scenario(name,records[name],config,True) for name in config['required_coarse_nominal']}
    step_ref,step_test=config['timestep_pair']
    step_allowance=abs(nominal[step_ref]['yield_fraction']-nominal[step_test]['yield_fraction'])
    pairs={}
    for label,names in config['refined_pairs'].items():
        coarse,fine=(scenario(name,records[name],config,True) for name in names)
        difference=abs(fine['yield_fraction']-coarse['yield_fraction'])
        floor=min(coarse['yield_fraction'],fine['yield_fraction'])-difference-step_allowance
        pairs[label]=dict(names=names,coarse=coarse,fine=fine,mesh_difference=difference,
                          conservative_mesh_screen=floor,
                          pass_screen=coarse['pass_diagnostics'] and fine['pass_diagnostics'] and floor>=threshold)
    stress={label:scenario(name,records[name],config,not label.endswith('zero_error'))
            for label,name in config['handoff_stress'].items()}
    controls={label:scenario(name,records[name],config,False)
              for label,name in config['reference_checks'].items()}
    env=config['envelope']
    speed=env['nonseed_min_speed_m_s']
    time=env['max_path_m']/speed
    drift=.5*env['charge_to_mass_per_V_C_kg']*env['charge_abs_tail_V']*time**2*(
        env['effective_electric_field_V_m']+speed*env['magnetic_field_uT']*1e-6)
    coarse_control=records[config['reference_checks']['coarse_control']]
    matched_initial_coarse={
        n:max(abs(records[n][k]/coarse_control[k]-1) for k in ('initial_energy_J','initial_mass_kg'))
        for n in nominal
    }
    passes=(max(matched_initial_coarse.values())<=1e-6 and all(d['pass_diagnostics'] and d['pass_yield'] for d in nominal.values()) and
            all(d['pass_screen'] for d in pairs.values()) and drift<=env['charge_drift_cap_m']
            and all(d['pass_yield'] and d['pass_diagnostics'] for d in controls.values())
            and all(d['pass_yield'] and d['pass_diagnostics'] for d in stress.values()))
    result=dict(simulation_screen_pass=passes,coarse_nominal=nominal,refined_pairs=pairs,
                reference_checks=controls,matched_initial_coarse_max_relative=matched_initial_coarse,separate_handoff_stress=stress,charge_bound_m=drift,timestep_allowance=step_allowance,
                earlier_handoff_clears_screen=all(d['pass_yield'] and d['pass_diagnostics']
                    for k,d in stress.items() if k.startswith('earlier')),
                metrology_pass=None)
    if metrology is not None:
        checks={}
        for k,maximum in config['limits'].items():
            value=metrology.get(k)
            checks[k]=valid_number(value) and 0<=value<=maximum
        for k in ('charge_abs_tail_V','effective_electric_field_V_m','magnetic_field_uT','max_path_m',
                  'charge_to_mass_per_V_C_kg'):
            value=metrology.get(k)
            checks[k]=valid_number(value) and 0<=value<=env[k]
        for k in ('effective_independent_groups_min','nonseed_min_speed_m_s'):
            value=metrology.get(k)
            checks[k]=valid_number(value) and value>=env[k]
        result.update(metrology_checks=checks,metrology_pass=all(checks.values()))
    return result


if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('budget',type=Path)
    p.add_argument('records',type=Path,help='directory containing the named JSON results')
    p.add_argument('--metrology',type=Path,help='measured nonnegative RMS values and coherent amplitudes')
    p.add_argument('--replay',help='print the runner arguments for one declared scenario')
    a=p.parse_args()
    config=read(a.budget)
    if a.replay:
        flags=[]
        for key,value in config['case_inputs'][a.replay].items():
            if value is not None:
                if key=='profile':
                    value=Path('data')/value
                flags.extend(('--'+key.replace('_','-'),str(value)))
        print(' '.join(flags))
        raise SystemExit(0)
    names=set(config['required_coarse_nominal'])|set(config['handoff_stress'].values())|set(config['reference_checks'].values())
    names.update(name for pair in config['refined_pairs'].values() for name in pair)
    missing=sorted(n for n in names if not (a.records/(n+'.json')).is_file())
    if missing:
        print(json.dumps(dict(simulation_screen_pass=None,pending_records=missing),indent=2))
        raise SystemExit(2)
    records={n:read(a.records/(n+'.json')) for n in names}
    result=assess(config,records,read(a.metrology) if a.metrology else None)
    print(json.dumps(result,indent=2,allow_nan=False))
    raise SystemExit(0 if result['simulation_screen_pass'] and result['metrology_pass'] is not False else 1)
