"""Freeze a location-balanced, development-only selection from UDE metadata."""
import collections,csv,hashlib,json,random
from pathlib import Path
from diatom_pilot.ude_development_archive import source_name_flags
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-scaleup';L=R/'results/r112/ude-sampling-metadata/exposure-ledger.csv';E=R/'results/r112/ude-sampling-metadata/exposure-report.json';M=Path('/tmp/ude-metadata.csv');sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 output=O/'selection.json';assert not output.exists();exposure=json.loads(E.read_text());assert exposure['ledger_sha256']==sha(L) and exposure['metadata_sha256']==sha(M);ledger={r['annotation_id']:r for r in csv.DictReader(L.open()) if r['exposure_status']=='prior_development'};pool=collections.defaultdict(lambda:collections.defaultdict(lambda:collections.defaultdict(list)))
 with M.open(encoding='utf-8-sig',newline='') as f:
  for r in csv.DictReader(f):
   source=ledger.get(r['annotation_id'])
   if not source or source_name_flags(source['genus'],source['species']):continue
   w=int(r['bbox_x1'])-int(r['bbox_x0'])+1;h=int(r['bbox_y1'])-int(r['bbox_y0'])+1
   if min(w,h)<15 or max(w,h)>4096 or w*h>16_000_000:continue
   key=(source['species'],source['genus']);pool[key][source['site_component']][source['image_filename']].append({'annotation_id':source['annotation_id'],'source_species':source['species'],'source_genus':source['genus'],'site_component':source['site_component'],'source_slide':source['image_filename'],'cutout_filename':source['cutout_filename'],'source_annotation_shape':source['annotation_shape'],'source_bbox_width_px':w,'source_bbox_height_px':h,'exposure_status':source['exposure_status']})
 eligible=[]
 for key,groups in pool.items():
  capacity=sum(min(10,sum(min(3,len(items)) for items in slides.values())) for slides in groups.values())
  if capacity>=50:eligible.append(key)
 assert len(eligible)==80;rng=random.Random(20261211);rows=[];counts={}
 for species,genus in sorted(eligible):
  locations=[]
  for group,slides in sorted(pool[(species,genus)].items()):
   choices=[]
   for slide,items in sorted(slides.items()):
    ordered=sorted(items,key=lambda x:x['annotation_id']);rng.shuffle(ordered);choices.extend(ordered[:3])
   rng.shuffle(choices);locations.append((group,choices[:10]))
  rng.shuffle(locations);chosen=[]
  while len(chosen)<50:
   progress=False
   for group,choices in locations:
    if choices and len(chosen)<50:chosen.append(choices.pop());progress=True
   if not progress:raise RuntimeError('Precomputed capacity mismatch')
  assert len(chosen)==50 and len({r['site_component'] for r in chosen})>=5 and max(collections.Counter(x['site_component'] for x in chosen).values())<=10 and max(collections.Counter(x['source_slide'] for x in chosen).values())<=3;rows.extend(chosen);counts[species]={'genus':genus,'crops':len(chosen),'site_components':len({x['site_component'] for x in chosen}),'slide_filenames':len({x['source_slide'] for x in chosen})}
 assert len(rows)==len({r['annotation_id'] for r in rows})==4000;result={'format':'r112-scaleup-selection-v1','seed':20261211,'ledger_sha256':sha(L),'exposure_report_sha256':sha(E),'ude_metadata_sha256':sha(M),'literal_name_guard_sha256':sha(R/'diatom_pilot/ude_development_archive.py'),'selection':'From site-component prior_development metadata only, keep source species strings with no simple morphotype/alternate/genus-mismatch syntax and with room for 50 crops under a max of 10 per conservative location component and max 3 per original slide. Exclude invalid/extreme bounding box dimensions. Select all 80 eligible source labels, round-robin across randomized components to 50 per label. Decisions use metadata, not pixel or model outcomes. This simple string filter does not reconcile taxonomy.','scope':'Development source candidates only. Published source names were assigned/reviewed by the UDE team, not independently adjudicated here. Source crop boxes are rough and can contain unlabelled organisms; no biological instance masks are provided. Any old test-candidate components, unknown locations and candidate unseen locations are excluded. This is not a validated training set or independent test.','per_name':counts,'records':rows};output.write_text(json.dumps(result,indent=2)+'\n');print('Frozen',len(rows),'crop IDs;',len(eligible),'source-name strings;',len({r['source_genus'] for r in rows}),'genera;',len({r['site_component'] for r in rows}),'location components')
if __name__=='__main__':main()
