"""Freeze multi-source, multi-background development scene recipes before rendering."""
import collections,hashlib,json,random
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r112/broad-background-scenes';B=R/'results/r112/academy-backgrounds-v2/manifest.json';T=R/'results/r112/taxonomy-audit/results.json';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 O.mkdir(parents=True,exist_ok=True);target=O/'protocol.json';assert not target.exists();spec=[('species-depth','development-assets.json'),('diversity-fetch','assets.json'),('breadth-depth','development-assets.json'),('new-taxa','development-assets.json')];pool=collections.defaultdict(list);inputs={str(B.relative_to(R)):sha(B),str(T.relative_to(R)):sha(T)};audit={x['source_name']:x['flags'] for x in json.loads(T.read_text())['records']}
 for dirname,assetname in spec:
  root=R/'results/r112'/dirname;afile=root/assetname;hfile=root/'mask-hypotheses/results.json';inputs[str(afile.relative_to(R))]=sha(afile);inputs[str(hfile.relative_to(R))]=sha(hfile);hyp={x['annotation_id']:x for x in json.loads(hfile.read_text())['records']}
  for r in json.loads(afile.read_text())['records']:
   h=hyp[r['annotation_id']]
   if h['triage']!='consistent-unverified':continue
   pool[r['source_species']].append({'record':r,'hypothesis':h,'asset_root':str(root.relative_to(R)),'mask_root':str((root/'mask-hypotheses').relative_to(R))})
 assert len(pool)==66 and sum(map(len,pool.values()))==442 and all(k in audit for k in pool)
 bg=json.loads(B.read_text())['records'];backgrounds=[]
 for r in bg:
  for im in r['images']:
   backgrounds.append({'slide':r['slide'],'slide_bytes':r['slide_bytes'],'origin_xy':r['origin_xy'],'z':im['z_index'],'path':str((B.parent/im['path']).relative_to(R)),'sha256':im['sha256'],'um_per_pixel_xy':r['um_per_pixel_xy']})
 assert len(backgrounds)==192;rng=random.Random(20261208);rng.shuffle(backgrounds);species=sorted(pool);extras=set(rng.sample(species,36));remaining={s:14+(s in extras) for s in species};queue={}
 for s in species:queue[s]=list(pool[s]);rng.shuffle(queue[s])
 schedule=[]
 for i,b in enumerate(backgrounds):
  count=(2,4,6,8)[i%4];rank=sorted((-remaining[s],rng.random(),s) for s in species if remaining[s]>0);assert len(rank)>=count;anchor=[rng.randrange(140,628),rng.randrange(140,628)];items=[]
  for j,(_,_,name) in enumerate(rank[:count]):
   remaining[name]-=1;obj=queue[name].pop(0);queue[name].append(obj);r=obj['record'];h=obj['hypothesis'];angle=rng.randrange(0,360,15);alpha=round(rng.uniform(.3,.85),8);contrast=round(rng.uniform(.65,1.35),8)
   if j==0 and i%4==0:center=[rng.choice([0,767]),rng.randrange(768)]
   elif j<3:center=[min(767,max(0,anchor[0]+rng.randrange(-70,71))),min(767,max(0,anchor[1]+rng.randrange(-70,71)))]
   else:center=[rng.randrange(768),rng.randrange(768)]
   items.append({'annotation_id':r['annotation_id'],'source_species':name,'source_genus':r['source_genus'],'source_slide_group':r['source_slide_group'],'source_asset_root':obj['asset_root'],'source_mask_root':obj['mask_root'],'source_original':r['source_crop'],'source_original_sha256':r['source_sha256'],'source_mask_center':h['masks']['center']['file'],'source_mask_center_sha256':h['masks']['center']['sha256'],'alternate_masks':{k:h['masks'][k] for k in ('minus','plus')},'source_um_per_pixel_xy':[.09,.09],'rotation_ccw_degrees':angle,'center_xy':center,'opacity':alpha,'contrast':contrast,'taxonomic_flags':audit[name]})
  schedule.append({'id':f'scene-{i:04d}','background':b,'instances':items})
 assert not any(remaining.values()) and sum(len(x['instances']) for x in schedule)==960;protocol={'format':'r112-broad-background-scenes-v1','seed':20261208,'inputs_sha256':inputs,'selection':'All 192 previously selected grayscale backgrounds, one scene per plane field. 2,4,6,8 placements cyclic; 14 or 15 per source-name string chosen by a balanced deterministic schedule; no duplicate source name within one scene. Source objects chosen by shuffled per-name cycling, not by visual quality. Source and taxonomy outputs are unverified development-only candidates.','rendering':'Old additive residual proxy with source 0.09 µm/px to target OME XY scale, 15-degree rotations, alpha 0.30–0.85, contrast 0.65–1.35, edge clipping and clustered positions; overlaps retain independent weak supports. No optical validation.','unknown':'All source masks and labels are unverified. Every original Academy background pixel, including under insertions, is unknown and may contain diatoms. Transparent visibility is undefined.','limits':'192 images reuse 64 spatial sites on 8 development slides and 3 neighboring Z indices per site. They are single-plane variants, not a validated 3-D synthetic Z stack; inserted 2-D sources do not model axial defocus. Source strings include possible synonyms and morphotypes and cannot be assumed distinct confirmed species. Filename-derived groups are not proven independent samples.','scenes':schedule};target.write_text(json.dumps(protocol,indent=2)+'\n');print('Frozen',len(schedule),'scenes, 960 placements,',len(pool),'source-name strings')
if __name__=='__main__':main()
