"""Freeze slide-grouped UDE species-depth source selection before image inspection."""
import collections,csv,hashlib,json,random
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-depth';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('Selection already exists; preserve it')
 prior_path=R/'results/r112/diversity-fetch/selection.json';prior=json.loads(prior_path.read_text());assert sha(META)==prior['metadata_sha256'];excluded=set(prior['excluded_previously_selected_slide_names'])|{r['source_slide'] for r in prior['rows']};prior_taxa={r['species'] for r in prior['rows']};by=collections.defaultdict(lambda:collections.defaultdict(list))
 with META.open(newline='',encoding='utf-8-sig') as f:
  for r in csv.DictReader(f):
   t=r['species'];slide=r['image_filename'].split('.Chunk')[0]
   if t not in prior_taxa or slide in excluded: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
   by[t][slide].append(r)
 viable={t:{slide:v for slide,v in groups.items() if len(v)>=5} for t,groups in by.items()};ranked=sorted((t for t,g in viable.items() if len(g)>=6),key=lambda t:(-sum(map(len,by[t].values())),t));chosen=ranked[:10];assert len(chosen)==10;rng=random.Random(20261204);assigned=set();rows=[];assignments=[]
 for t in sorted(chosen,key=lambda t:(len(viable[t]),t)):
  choices=sorted(set(viable[t])-assigned)
  if len(choices)<6:raise RuntimeError(f'Not enough distinct slide groups remaining for {t}')
  slides=rng.sample(choices,6);assigned.update(slides)
  for n,slide in enumerate(slides):
   split='development' if n<4 else ('validation_candidate' if n==4 else 'test_candidate');items=rng.sample(sorted(viable[t][slide],key=lambda x:x['annotation_id']),5);assignments.append({'species':t,'slide':slide,'split':split})
   for r in items:rows.append({'split':split,'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)==300 and len({x['annotation_id'] for x in rows})==300 and len(assigned)==60;data={'format':'ude-four-species-development-v1','purpose':'R112 species-depth development with provisional slide-held-out validation/test candidates. Not biologically independent until source sample relations and near-duplicates are verified.','seed':20261204,'metadata_sha256':sha(META),'earlier_selection_sha256':sha(prior_path),'excluded_previously_inspected_slide_names':sorted(excluded),'selection':'Choose ten most frequent viable species among previous 30 after excluding previously selected slide-name groups, then choose six unique never-reused slide names per species and five crops each. Assign four source slides development, one validation candidate, one test candidate; no slide appears in two groups or taxa. Metadata-only, nonrepresentative; all candidate partitions provisional.','source_taxa':chosen,'slide_group_assignments':assignments,'all_biological_independence':'unknown; different slide names are not proof of independent biological samples','final_test_status':'candidate only; no model selection, training or user-facing image previews; sample provenance and leakage audit required','rows':rows};out.write_text(json.dumps(data,indent=2)+'\n');print('Frozen',len(rows),'crops;',len(chosen),'species;',len(assigned),'disjoint slide names; counts',dict(collections.Counter(x['split'] for x in rows)))
if __name__=='__main__':main()
