"""Verify downloadable controller summaries without internal source files."""
from pathlib import Path
import csv,json,math,statistics
P=Path(__file__).resolve().parent
with (P/'stored-trials.csv').open(newline='',encoding='utf-8-sig') as f:rows=list(csv.DictReader(f))
a=json.loads((P/'aggregate.json').read_text(encoding='utf-8'))
assert len(rows)==100
for i,r in enumerate(rows):
 assert int(r['trial'])==i+1
 for key in ['within_endpoint_threshold','event1_within_threshold','event2_within_threshold','event3_within_threshold']:assert r[key]in('0','1')
 for key in ['endpoint_absolute_lateral_error_m','median_postupdate_absolute_lateral_error_m','mean_matches_per_frame']:assert math.isfinite(float(r[key])) and float(r[key])>=0
 assert int(r['within_endpoint_threshold'])==(float(r['endpoint_absolute_lateral_error_m'])<=a['thresholds']['endpoint_absolute_error_m'])
n=len(rows);hits=sum(int(r['within_endpoint_threshold'])for r in rows);events=sum(int(r[k])for r in rows for k in ['event1_within_threshold','event2_within_threshold','event3_within_threshold'])
calc=dict(trials=n,endpoint_within_threshold_count=hits,endpoint_within_threshold_fraction=hits/n,median_of_trial_median_absolute_errors_m=statistics.median(float(r['median_postupdate_absolute_lateral_error_m'])for r in rows),endpoint_error_nearest_rank_p95_m=sorted(float(r['endpoint_absolute_lateral_error_m'])for r in rows)[math.ceil(.95*n)-1],events_with_threshold_hit=events,events_total=3*n,event_threshold_hit_fraction=events/(3*n),mean_matches_per_frame=sum(float(r['mean_matches_per_frame'])for r in rows)/n)
for k,v in calc.items():assert math.isclose(v,a['controller_aggregates'][k],rel_tol=1e-14,abs_tol=1e-14),(k,v,a['controller_aggregates'][k])
print(json.dumps(dict(status='pass',controller_rows=n,stored_event_flags=3*n,aggregate_fields_checked=len(calc),scope='CSV consistency only; no simulation rerun, baseline reproduction or event-trajectory reconstruction'),indent=2))
