"""Numerical identities, limiting controls and explicit component requirements."""
from pathlib import Path
import json,hashlib
from scipy.optimize import brentq
import cold_pressure_loop as C
R=Path(__file__).resolve().parents[1]
def main():
    loop=json.loads((R/'output/cold-pressure-loop.json').read_text())
    reheat=json.loads((R/'output/reheated-cycle.json').read_text())
    recovery=json.loads((R/'output/recuperated-pressure.json').read_text())
    checks=[]
    for name,rows in [('cold-pressure-loop',loop['cases']),('reheated-expansion',reheat['cases']),('recuperated-pressure',recovery['cases'])]:
        key='complete_steady_first_law_residual_J' if name=='reheated-expansion' else 'complete_first_law_residual_J'
        for row in rows:
            assert abs(row[key])<1e-6
            assert abs(row['exergy_entropy_identity_residual_J'])<1e-6
        checks.append({'record':name,'states':len(rows),'energy_and_exergy_identity_max_residual_J':max(max(abs(z[key]),abs(z['exergy_entropy_identity_residual_J'])) for z in rows)})
    stopped=C.cycle(et=0,coupling='shaft')
    assert stopped['generator_DC_J']==0 and stopped['net_steady_DC_J']<0
    saved=C.EG;C.EG=0
    zero_generator=C.cycle(coupling='shaft');C.EG=saved
    assert zero_generator['net_steady_DC_J']<0
    requirements={
       'same_shaft_maximum_hot_air_pressure_loss_Pa_for_nonnegative_steady_DC':brentq(lambda p:C.cycle(air_dp=p,coupling='shaft')['net_steady_DC_J'],0,2000,xtol=1e-7),
       'electrical_control_maximum_hot_air_pressure_loss_Pa_for_nonnegative_steady_DC':brentq(lambda p:C.cycle(air_dp=p)['net_steady_DC_J'],0,2000,xtol=1e-7),
       'same_shaft_maximum_cold_compressor_inlet_K_for_nonnegative_steady_DC':brentq(lambda t:C.cycle(cold=t,coupling='shaft')['net_steady_DC_J'],90,140,xtol=1e-8),
       'same_shaft_equal_turbine_and_compressor_isentropic_efficiency_floor':brentq(lambda e:C.cycle(et=e,ec=e,coupling='shaft')['net_steady_DC_J'],.6,.9,xtol=1e-9),
       'interpretation':'Break-even requirements hold with all other selected inputs fixed. No startup, mass or installed machine qualification.'}
    out={'physical_measurements':0,'status':'PASSED_NUMERICAL_IDENTITIES_AND_LIMITING_CONTROLS',
         'state_checks':checks,'zero_turbine_net_J':stopped['net_steady_DC_J'],
         'zero_generator_net_J':zero_generator['net_steady_DC_J'],'pressure_loop_requirements':requirements,
         'sources':[{'path':'scripts/'+p.name,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()} for p in [R/'scripts/cold_pressure_loop.py',R/'scripts/reheated_cycle.py',R/'scripts/recuperated_pressure.py']],
         'interpretation':'These checks establish numerical consistency of the declared thermodynamic screens. They are not measured efficiencies, reliability trials or physical validation.'}
    (R/'output/thermal-audit.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2))
if __name__=='__main__':main()
