"""Assign conservative site-level exposure statuses; never load UDE image pixels."""
import collections,csv,hashlib,json
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r112/ude-sampling-metadata';M=Path('/tmp/ude-metadata.csv');C=O/'site-components.json';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def canonical(s):
 s=s.strip().replace('\\','/').split('/')[-1].casefold();return s[:-5] if s.endswith('.tiff') else s[:-4] if s.endswith('.tif') else s
paths=[R/x for x in ['results/r112/diversity-fetch/selection.json','results/r112/species-depth/selection.json','results/r112/breadth-depth/selection.json','results/r112/new-taxa/selection.json','results/pilot/ude-adaptation/selection.json','results/pilot/ude-adaptation-within-genus/selection.json','results/r14/prefix/reference-manifest.json','results/r7/reference-manifest.json']];used=set();legacy=set()
for p in paths:
 obj=json.loads(p.read_text());rows=obj if isinstance(obj,list) else obj['rows']
 for row in rows:
  if p==R/'results/r112/species-depth/selection.json' and row['split']=='test_candidate':legacy.add(row['annotation_id'])
  else:used.add(row['annotation_id'])
components=json.loads(C.read_text());lookup={key:c['component_id'] for c in components['components'] for key in c['slide_keys']};metadata=[];found=set()
with M.open(encoding='utf-8-sig',newline='') as f:
 for r in csv.DictReader(f):
  x={'annotation_id':r['annotation_id'],'image_filename':r['image_filename'],'cutout_filename':r['cutout_filename'],'genus':r['genus'],'species':r['species'],'subspecies':r['subspecies'],'annotator':r['annotator'],'annotation_shape':r['shape'],'site_component':lookup.get(canonical(r['image_filename'])) or ''};metadata.append(x)
  if x['annotation_id'] in used or x['annotation_id'] in legacy:found.add(x['annotation_id'])
assert found==used|legacy and len(metadata)==len({x['annotation_id'] for x in metadata})==83570;used_groups={r['site_component'] for r in metadata if r['annotation_id'] in used and r['site_component']};legacy_groups={r['site_component'] for r in metadata if r['annotation_id'] in legacy and r['site_component']};status={}
for c in components['components']:
 g=c['component_id'];status[g]='legacy_reserved_conflict' if g in legacy_groups and g in used_groups else 'legacy_reserved' if g in legacy_groups else 'prior_development' if g in used_groups else 'candidate_unseen_location'
counts=collections.Counter();taxa=collections.defaultdict(set)
with (O/'exposure-ledger.csv').open('w',newline='') as f:
 fields=['annotation_id','image_filename','cutout_filename','genus','species','subspecies','annotator','annotation_shape','site_component','exposure_status'];writer=csv.DictWriter(f,fieldnames=fields);writer.writeheader()
 for row in metadata:
  row['exposure_status']=status[row['site_component']] if row['site_component'] else 'unmatched_slide_quarantine';writer.writerow(row);counts[row['exposure_status']]+=1
  if row['species'].strip() not in ('','None'):taxa[row['exposure_status']].add(row['species'])
groups=collections.Counter(status.values());result={'format':'r112-ude-exposure-ledger-v1','component_sha256':sha(C),'metadata_sha256':sha(M),'input_manifests_sha256':{str(p.relative_to(R)):sha(p) for p in paths},'script_sha256':sha(Path(__file__)),'ledger_sha256':sha(O/'exposure-ledger.csv'),'metadata_rows':len(metadata),'status_counts':dict(counts),'component_counts':dict(groups),'distinct_source_species_strings':{k:len(v) for k,v in taxa.items()},'previously_seen_or_selected_annotation_ids':len(used),'legacy_test_candidate_ids':len(legacy),'known_prior_unmatched_ids':sorted(r['annotation_id'] for r in metadata if r['annotation_id'] in used|legacy and not r['site_component']),'policy':'A component containing any prior R112 species-depth test candidate is excluded from new training. If a component also contains prior development images, it is labeled legacy_reserved_conflict and is not location-independent. Components without a known selection in these eight audited manifests are candidate_unseen_location, not automatically valid test data; protect them from training while a complete exposure and sample audit is performed. Unmatched slides are quarantined. No UDE image pixels are loaded.','limitations':'Prior-use audit is limited to explicitly listed manifests and may miss other previous access. Site-code/coordinate components are conservative proxies, not guaranteed biological sampling units; same site does not necessarily mean same sample, and distinct sites do not guarantee independence. Other taxa, genus-only entries and taxonomy synonyms are not adjudicated.'};(O/'exposure-report.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps({k:result[k] for k in ('metadata_rows','status_counts','component_counts','distinct_source_species_strings','known_prior_unmatched_ids')},indent=2))
