"""Select underrepresented UDE development names with explicit site/slide caps."""
import collections,csv,json,random
from pathlib import Path
from diatom_pilot.ude_development_archive import source_name_flags
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-breadth';D=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')
def main():
 assert not (O/'selection.json').exists();exposure=json.loads(E.read_text());assert exposure['ledger_sha256']==sha(L) and exposure['metadata_sha256']==sha(M);old=json.loads((D/'selection.json').read_text());oldnames=set(old['per_name']);oldgenera={x['genus'] for x in old['per_name'].values()};ledger={r['annotation_id']:r for r in csv.DictReader(L.open()) if r['exposure_status']=='prior_development' and not source_name_flags(r['genus'],r['species']) and r['species'] not in oldnames};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):
   src=ledger.get(r['annotation_id'])
   if not src: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=(src['species'],src['genus']);pool[key][src['site_component']][src['image_filename']].append({'annotation_id':src['annotation_id'],'source_species':src['species'],'source_genus':src['genus'],'site_component':src['site_component'],'source_slide':src['image_filename'],'cutout_filename':src['cutout_filename'],'source_annotation_shape':src['annotation_shape'],'source_bbox_width_px':w,'source_bbox_height_px':h,'exposure_status':src['exposure_status']})
 eligible=[]
 for key,groups in pool.items():
  capacity=sum(min(4,sum(min(2,len(items)) for items in slides.values())) for slides in groups.values())
  if len(groups)>=3 and capacity>=8:eligible.append(key)
 assert len(eligible)==137;rng=random.Random(11281026);rows=[];counts={}
 for species,genus in sorted(eligible):
  groups=[]
  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[:2])
   rng.shuffle(choices);groups.append((group,choices[:4]))
  rng.shuffle(groups);chosen=[]
  while len(chosen)<8:
   progress=False
   for group,choices in groups:
    if choices and len(chosen)<8:chosen.append(choices.pop());progress=True
   if not progress:raise RuntimeError('Capacity mismatch')
  assert len({x['site_component'] for x in chosen})>=3 and max(collections.Counter(x['site_component'] for x in chosen).values())<=4 and max(collections.Counter(x['source_slide'] for x in chosen).values())<=2;rows.extend(chosen);counts[species]={'genus':genus,'crops':8,'site_components':len({x['site_component'] for x in chosen}),'slide_filenames':len({x['source_slide'] for x in chosen}),'genus_new_to_80_name_pool':genus not in oldgenera}
 assert len(rows)==len({x['annotation_id'] for x in rows})==1096;result={'format':'r112-species-breadth-selection-v1','seed':11281026,'inputs_sha256':{str(L.relative_to(R)):sha(L),str(E.relative_to(R)):sha(E),'results/r112/species-scaleup/selection.json':sha(D/'selection.json'),'diatom_pilot/ude_development_archive.py':sha(R/'diatom_pilot/ude_development_archive.py'),'research/r112_species_breadth_select.py':sha(__file__)},'metadata_sha256':sha(M),'selection':'Metadata-only selection from prior_development components. Exclude old 80 exact source-name strings, qualified/morphotype/alternate/genus-mismatch syntax, and invalid/extreme crop bounds. Include every other name with capacity for eight crops from at least three conservative components, with max four per component and two per slide; round-robin across randomized components. Exact source-name strings can still be synonyms or disputed names.','warning':'Development source candidates only; public dataset names not independently reconciled with Academy taxonomy, location groups do not establish independence, original images may contain neighboring organisms and there are no validated masks. Protect candidate unseen locations and all reserved/quarantined components. Eight examples per name is low and some source crops were used before.','per_name':counts,'records':rows};(O/'selection.json').write_text(json.dumps(result,indent=2)+'\n');print('selected',len(rows),'crops;',len(counts),'additional source strings;',len({r['source_genus'] for r in rows}),'source genera;',len({r['source_genus'] for r in rows}-oldgenera),'new genera')
if __name__=='__main__':main()
