"""Compare independent fixed-column PDB/SciPy results against the mmCIF/native-session table."""
from pathlib import Path
from datetime import datetime,timezone
import csv,json
root=Path(__file__).resolve().parents[1]
def run():
    main=list(csv.DictReader((root/'results/structural_comparison.csv').open()))
    audit=json.loads((root/'independent/reference_fit.json').read_text())
    fields={'n_fit':'n_fit_CA','n_global':'n_compared_CA','n_wpd':'n_loop_CA','fit_rmsd_A':'fit_rmsd_A','global_rmsd_A':'rmsd_all_CA_2_280_A','wpd_rmsd_A':'loop_176_187_rmsd_fitted_frame_A','asp181_delta_A':'asp181_CA_displacement_A'}
    records=[]
    for test in audit:
        rows=[r for r in main if r['reference']==test['reference'] and r['mobile']==test['mobile'] and r['fit_definition']=='core_2-280_excl_176-187' and r['altloc_policy']=='highest_occupancy']
        assert len(rows)==1
        for key,column in fields.items():
            delta=abs(test[key]-float(rows[0][column]))
            records.append(dict(pair=[test['reference'],test['mobile']],measure=key,independent=test[key],primary=float(rows[0][column]),absolute_difference=delta,passed=delta<1e-6))
    assert len(records)==21 and all(r['passed'] for r in records)
    (root/'independent/primary_agreement.json').write_text(json.dumps(dict(checked_utc=datetime.now(timezone.utc).isoformat(),tolerance=1e-6,checks=records),indent=2))
    print('Independent audit passed:',len(records),'checks')
if __name__=='__main__':run()
