"""Freeze metadata-only selection of diverse UDE development crops."""
import collections,csv,hashlib,json,random
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r112/diversity-fetch';META=Path('/tmp/ude-metadata.csv')
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 out=O/'selection.json'
 if out.exists():raise FileExistsError('Frozen selection already exists')
 previous=json.loads((R/'results/pilot/ude-adaptation-within-genus/selection.json').read_text());assert sha(META)==previous['metadata_sha256'];exclude={r['source_slide'] for r in previous['rows']};prefix=json.loads((R/'results/r14/prefix/reference-manifest.json').read_text());exclude.update(r['source_slide'] for r in prefix['rows']);ref=json.loads((R/'results/r7/reference-manifest.json').read_text());exclude.update(r['source_slide'] for r in ref);by=collections.defaultdict(lambda:collections.defaultdict(list));genus={}
 with META.open(newline='',encoding='utf-8-sig') as f:
  for r in csv.DictReader(f):
   taxon=r['species'].strip();g=r['genus'].strip();slide=r['image_filename'].split('.Chunk')[0];
   if taxon in ('','None') or g in ('','None') or slide in exclude:continue
   w=int(r['bbox_x1'])-int(r['bbox_x0']);h=int(r['bbox_y1'])-int(r['bbox_y0'])
   if not 60<=max(w,h)<=800 or min(w,h)<15:continue
   if taxon in genus and genus[taxon]!=g:continue
   genus[taxon]=g;by[taxon][slide].append(r)
 eligible={t:groups for t,groups in by.items() if len(groups)>=4};counts={t:sum(map(len,groups.values())) for t,groups in eligible.items()};chosen=[]
 for name in ('Achnanthidium minutissimum','Achnanthidium jackii','Navicula gregaria','Navicula lanceolata'):
  if name not in eligible:raise RuntimeError('required source species missing from eligible pool: '+name)
  chosen.append(name)
 other={}
 for t in eligible:
  g=genus[t]
  if g in ('Achnanthidium','Navicula'):continue
  if g not in other or (-counts[t],t)<(-counts[other[g]],other[g]):other[g]=t
 other_taxa=sorted(other.values(),key=lambda t:(-counts[t],t))[:26];assert len(other_taxa)==26;chosen.extend(other_taxa);rng=random.Random(20261203);rows=[]
 for t in chosen:
  groups=by[t];slides=rng.sample(sorted(groups),4)
  for slide in slides:
   r=rng.choice(sorted(groups[slide],key=lambda x:x['annotation_id']));rows.append({'split':'development','source_slide':slide,'species':r['species'],'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(rows)==120 and len({r['annotation_id'] for r in rows})==120
 result={'format':'ude-four-species-development-v1','purpose':'R112 metadata-only diverse development source acquisition; not a train/validation/test split or an independent evaluation set.','seed':20261203,'metadata_sha256':sha(META),'excluded_previously_selected_slide_names':sorted(exclude),'selection':'Four target species from two genera plus most-represented eligible species from 26 other genera; four distinct filename-derived slides per taxon; one randomized crop per slide; previously selected slides excluded. Based on metadata only, selection is nonrepresentative.','source_taxon_count':len(chosen),'source_genus_count':len({genus[t] for t in chosen}),'all_biological_independence':'unknown; filename-derived slide groups are proxies','source_taxa_unverified':True,'rows':rows};O.mkdir(parents=True,exist_ok=True);out.write_text(json.dumps(result,indent=2)+'\n');print('Selected',len(rows),'crops;',len(chosen),'source species;',result['source_genus_count'],'genera;',len({r['source_slide'] for r in rows}),'filename-derived slides; all development only.')
if __name__=='__main__':main()
