"""Compare independent computations against the study's numerical files."""
import csv
import json
import subprocess
import sys
from decimal import Decimal as D
from pathlib import Path

root=Path(sys.argv[1]).resolve()
code=Path(__file__).resolve().with_name('numeric_audit.py')
ref=json.loads(subprocess.check_output([sys.executable,str(code),str(root)]))
rows=[]
def test(name, measured, expected, tolerance, source):
    a,b=D(str(measured)),D(str(expected))
    err=abs(a-b)
    rows.append(dict(quantity=name,study_value=str(a),external_value=str(b),
                     absolute_difference=str(err),absolute_tolerance=str(tolerance),
                     passed=err <= D(str(tolerance)),study_file=source))
def result(file):
    return json.loads((root/'results'/file).read_text())
s=result('slope_constants.json')
for field,key in [('Lambda_V','lambda_v'),('x_star','band_tip'),('s_tangency','band_tip')]:
    test(field,s[field],ref[key],'1e-23','results/slope_constants.json')
for r in csv.DictReader((root/'results/gamma_tip.csv').open()):
    if r['s'] in ref['slit_tip_coefficients']:
        test('Slit coefficient s='+r['s'],r['gamma_tip'],ref['slit_tip_coefficients'][r['s']],'1e-14','results/gamma_tip.csv')
for f in sorted((root/'results').glob('functional_c*.json')):
    d=json.loads(f.read_text())
    if str(d['c']) not in ref['finite_order_P2_gap']:continue
    point=next((r for r in d['results'] if r['P']==2),None)
    if point:
        test(f"P=2 cubic gap c={d['c']}",point['Delta1'],ref['finite_order_P2_gap'][str(d['c'])],'2e-22','results/'+f.name)
hp=result('hp_hagedorn.json')
for field,key in [('beta_0','Hagedorn_beta_over_R'),('T_H0','Hagedorn_free_TR'),('y_H','y_H')]:
    test(field,hp[field],ref[key],'1e-14','results/hp_hagedorn.json')
quartic = result('hp_quartic.json')
for i,piece in enumerate(('a','b')):
    test('Appendix B finite sum '+piece,quartic['series'][piece]['partial'],
         ref['appendix_B_truncated'][i],'1e-14','results/hp_quartic.json')
for field,key,tol in [('I','I_from_published_inputs','1e-14'),
                      ('q4_crit','sign_change_q4','1e-13'),
                      ('b_over_lambda2','b_over_lambda_squared_from_published_inputs','1e-16')]:
    test(field,quartic['quartic'][field],ref[key],tol,'results/hp_quartic.json')
table = {int(r['c']):r for r in csv.DictReader((root/'results/table2_extracted.csv').open())}
test('Table 2 rows',len(table),ref['finite_c_rows'],0,'results/table2_extracted.csv')
for endpoint in ref['finite_c_endpoints']:
    c=endpoint['c']
    test('Finite-c denominator at c='+str(c),table[c]['ratio_recomputed'],endpoint['denominator'],
         '1e-13','results/table2_extracted.csv')
print(json.dumps({'scope':'Independent external numeric audit of the specified quantities. Optimizer rows beyond P=2 and the complete optimality proof are outside this check.','method':'Decimal arithmetic, spherical-harmonic sums, direct root bracketing, an analytic reduction of the general-slit tip integral and source-table reassembly.','pass':all(r['passed'] for r in rows),'checks':rows},indent=2))
