#!/usr/bin/env python3
from __future__ import annotations
import math
from common import load_manifest, rmse, write_receipt

def planck_thermal_mode(x:float)->float:
    return x/math.expm1(x)

def boyer_total_mode(x:float)->float:
    return 0.5*x/math.tanh(0.5*x)

def boyer_thermal_mode(x:float)->float:
    return boyer_total_mode(x)-0.5*x

def main()->dict:
    m=load_manifest('blackbody-v1.json')
    xs=[0.05+i*(11.95/239) for i in range(240)]
    residuals=[boyer_thermal_mode(x)-planck_thermal_mode(x) for x in xs]
    worst_i=max(range(len(xs)),key=lambda i:abs(residuals[i]))
    x_hi=12.0; p_hi=planck_thermal_mode(x_hi); rj_hi=1.0
    formula_rmse=rmse(residuals); ratio=rj_hi/p_hi
    ok=formula_rmse<=m['tolerances']['formula_rmse'] and ratio>=m['tolerances']['high_frequency_rj_failure_min_ratio']
    receipt={'schema':'classical-reconstruction-receipt/v1','benchmark_id':m['benchmark_id'],'ok':ok,
      'ontology_contract_sha256':m['ontology_contract_sha256'],'sample_count':len(xs),
      'formula_level':{'boyer_total':'x/2*coth(x/2)','zero_point':'x/2','thermal_remainder':'x/(exp(x)-1)'},
      'planck_vs_boyer_thermal_rmse':formula_rmse,'worst_residual':{'x':xs[worst_i],'value':residuals[worst_i]},
      'rayleigh_jeans_high_frequency_failure':{'x':x_hi,'rj_mode_energy_over_kT':rj_hi,'planck_mode_energy_over_kT':p_hi,'rj_to_planck_ratio':ratio},
      'q1_q5':m['q1_q5'],'scope_exclusion':m['scope_exclusion'],'sources':m['sources']}
    write_receipt('blackbody-v1.json',receipt); return receipt
if __name__=='__main__':
    import json; print(json.dumps(main(),indent=2))
