"""Freeze extra development sources for underrepresented taxa using metadata only."""
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/breadth-depth';sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 O.mkdir(parents=True,exist_ok=True);target=O/'selection.json';assert not target.exists();div=R/'results/r112/diversity-fetch/selection.json';deep=R/'results/r112/species-depth/selection.json';a=json.loads(div.read_text());b=json.loads(deep.read_text());assert sha(M)==a['metadata_sha256']==b['metadata_sha256'];alltaxa={x['species'] for x in a['rows']};depthtaxa={x['species'] for x in b['rows']};taxa=sorted(alltaxa-depthtaxa);assert len(taxa)==20;exclude=set(a['excluded_previously_selected_slide_names'])|{x['source_slide'] for x in a['rows']}|{x['source_slide'] for x in b['rows']};by=collections.defaultdict(lambda:collections.defaultdict(list))
 with M.open(encoding='utf-8-sig',newline='') as f:
  for r in csv.DictReader(f):
   t=r['species'];slide=r['image_filename'].split('.Chunk')[0]
   if t not in taxa or slide in exclude:continue
   w=int(r['bbox_x1'])-int(r['bbox_x0']);h=int(r['bbox_y1'])-int(r['bbox_y0'])
   if 60<=max(w,h)<=800 and min(w,h)>=15:by[t][slide].append(r)
 rng=random.Random(20261206);rows=[];assigned=set();assignments=[]
 for t in sorted(taxa,key=lambda x:(len(by[x]),x)):
  choices=sorted(set(by[t])-assigned);slides=rng.sample(choices,min(4,len(choices)))
  for slide in slides:
   assigned.add(slide);candidates=sorted(by[t][slide],key=lambda x:x['annotation_id']);chosen=rng.sample(candidates,min(3,len(candidates)));assignments.append({'species':t,'slide':slide,'count':len(chosen)})
   for r in chosen:rows.append({'split':'development','source_slide':slide,'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(rows)==len({x['annotation_id'] for x in rows}) and len({x['species'] for x in rows})==20
 p={'format':'ude-four-species-development-v1','purpose':'Development-only acquisition to increase depth in the 20 source-named taxa missing from the existing 10-taxon depth pool.','seed':20261206,'metadata_sha256':sha(M),'earlier_selections':{str(div.relative_to(R)):sha(div),str(deep.relative_to(R)):sha(deep)},'selection':'Metadata only: exclude prior and all held-out filename groups; sort target taxa by available groups; sample up to four distinct unassigned filename groups per species and up to three crops per group. This is nonrepresentative.','slide_group_assignments':assignments,'limitations':'Filename groups do not prove biological sample independence, source species are unverified, neighboring organisms possible. No candidate validation or test images are selected.','rows':rows};target.write_text(json.dumps(p,indent=2)+'\n');print('Frozen',len(rows),'crops,',len(assigned),'new slide names;',len(taxa),'species; counts',dict(collections.Counter(x['species'] for x in rows)))
if __name__=='__main__':main()
