"""Freeze additional UDE species candidates with at least two unused slide names."""
import collections,csv,hashlib,json,random
from pathlib import Path
R=Path(__file__).resolve().parents[1];M=Path('/tmp/ude-metadata.csv');O=R/'results/r112/new-taxa';sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
def canonical(s):return s.rsplit('.',1)[0] if s.lower().endswith(('.tif','.tiff')) else s
def main():
 O.mkdir(exist_ok=True,parents=True);out=O/'selection.json';assert not out.exists();paths=[R/'results/r112/diversity-fetch/selection.json',R/'results/r112/species-depth/selection.json',R/'results/r112/breadth-depth/selection.json'];data=[json.loads(x.read_text()) for x in paths];assert all(x['metadata_sha256']==sha(M) for x in data);excluded=set(data[0]['excluded_previously_selected_slide_names']);taxa=set();genera=set()
 for d in data:
  for r in d['rows']:excluded.add(r['source_slide']);taxa.add(r['species']);genera.add(r['genus'])
 excluded={canonical(x) for x in excluded};by=collections.defaultdict(lambda:collections.defaultdict(list)); genus={};ambiguous=set()
 with M.open(encoding='utf-8-sig',newline='') as f:
  for r in csv.DictReader(f):
   t=r['species'].strip();g=r['genus'].strip();slide=r['image_filename'].split('.Chunk')[0];w=int(r['bbox_x1'])-int(r['bbox_x0']);h=int(r['bbox_y1'])-int(r['bbox_y0'])
   if t in taxa or t in ('','None') or g in ('','None') or canonical(slide) in excluded or not(60<=max(w,h)<=800 and min(w,h)>=15):continue
   if t in genus and genus[t]!=g:ambiguous.add(t)
   genus[t]=g;by[t][canonical(slide)].append(r)
 selected=sorted(t for t in by if t not in ambiguous and len(by[t])>=2);rng=random.Random(20261207);rows=[];assignments=[]
 for t in selected:
  for group in rng.sample(sorted(by[t]),2):
   candidates=sorted(by[t][group],key=lambda x:x['annotation_id']);chosen=rng.sample(candidates,min(2,len(candidates)));assignments.append({'species':t,'canonical_slide':group,'count':len(chosen)})
   for r in chosen:rows.append({'split':'development','source_slide':r['image_filename'].split('.Chunk')[0],'species':t,'genus':r['genus'],'subspecies':r['subspecies'],'annotation_id':r['annotation_id'],'image_id':r['image_id'],'filename':r['cutout_filename'],'local_file':f"images/{r['annotation_id']}.png",'source_annotation_shape':r['shape']})
 assert len(selected)==36 and len(rows)==len({r['annotation_id'] for r in rows})
 output={'format':'ude-four-species-development-v1','purpose':'Metadata-selected development-only expansion to source-named taxa not represented in previous 30 species.','seed':20261207,'metadata_sha256':sha(M),'prior_selections':{str(x.relative_to(R)):sha(x) for x in paths},'selection':'All eligible previously unselected source-named species with at least two canonical filename-derived slide groups not used in earlier pools; randomly choose two groups and up to two crops per group. Groups can occur in multiple development taxa; species and images are not selected by visual/model results.','assigned_groups':assignments,'limitations':'Two filename groups do not establish separate biological samples. Source names and rough annotations are unverified; crops can contain unlabeled neighbors. Existing validation/test groups excluded, but coarse filename and image screening cannot rule out related specimens.','rows':rows};out.write_text(json.dumps(output,indent=2)+'\n');print('Frozen',len(rows),'crops,',len(selected),'taxa,',len({r['genus'] for r in rows}),'genera;',len({r['genus'] for r in rows}-genera),'genera new; group count',len({canonical(r['source_slide']) for r in rows}))
if __name__=='__main__':main()
