"""Replay breadth source selection without reading specimen pixels."""
import collections,csv,json,tempfile
from pathlib import Path
import r112_species_breadth_select as selector
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-breadth';p=json.loads((O/'selection.json').read_text());ledger={r['annotation_id']:r for r in csv.DictReader((R/'results/r112/ude-sampling-metadata/exposure-ledger.csv').open())};old=json.loads((R/'results/r112/species-scaleup/selection.json').read_text());assert p['metadata_sha256']==sha(Path('/tmp/ude-metadata.csv'))
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h,f
rows=p['records'];seen=set();names=collections.Counter();sites=collections.defaultdict(collections.Counter);slides=collections.defaultdict(collections.Counter)
for r in rows:
 ident=r['annotation_id'];assert ident not in seen;seen.add(ident);v=ledger[ident];assert v['exposure_status']=='prior_development' and (v['species'],v['genus'],v['site_component'],v['image_filename'])==(r['source_species'],r['source_genus'],r['site_component'],r['source_slide']);assert r['source_species'] not in old['per_name'] and not selector.source_name_flags(r['source_genus'],r['source_species']);names[r['source_species']]+=1;sites[r['source_species']][r['site_component']]+=1;slides[r['source_species']][r['source_slide']]+=1
assert len(seen)==1096 and len(names)==137 and set(names.values())=={8} and all(len(s)>=3 and max(s.values())<=4 for s in sites.values()) and all(max(s.values())<=2 for s in slides.values())
with tempfile.TemporaryDirectory(prefix='r112-breadth-replay-',dir='/tmp') as tmp:
 selector.O=Path(tmp);selector.main();assert (selector.O/'selection.json').read_bytes()==(O/'selection.json').read_bytes()
report={'format':'r112-species-breadth-selection-verify-v1','selection_sha256':sha(O/'selection.json'),'records':len(seen),'source_name_strings':len(names),'checks':'Input hashes, all metadata-only exposure statuses, exclusion of previous 80 exact names, per-name source and location limits, and byte-identical full deterministic selection replay verified. This does not establish biological independence, name validity, or image quality.'};(O/'selection-verify.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
