"""Freeze split-respecting synthetic scene recipes after cross-partition screening."""
import collections,hashlib,json,random
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r112/grouped-synthetic';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 target=O/'scene-protocol.json';assert not target.exists();split=json.loads((O/'split.json').read_text());screen=json.loads((O/'similarity-screen.json').read_text());assert screen['protocol_sha256']==sha(O/'screen-protocol.json') and json.loads((O/'screen-protocol.json').read_text())['split_sha256']==sha(O/'split.json');q=set(screen['quarantined_ids']);pool={'train':collections.defaultdict(list),'validation':collections.defaultdict(list)}
 for r in split['sources']:
  if r['annotation_id'] not in q:pool[r['synthetic_partition']][r['source_species']].append(r)
 overlap=set(pool['train'])&set(pool['validation']);assert len(overlap)>0;rng=random.Random(20261209);scenes=[];num={}
 for partition in ('train','validation'):
  names=sorted(pool[partition] if partition=='train' else overlap);bg=[r for r in split['backgrounds'] if r['synthetic_partition']==partition];rng.shuffle(bg);assert len(bg)%4==0;nplaces=len(bg)*5;minct,extra=divmod(nplaces,len(names));extras=set(rng.sample(names,extra));remaining={s:minct+(s in extras) for s in names};queues={}
  for name in names:queues[name]=list(pool[partition][name]);rng.shuffle(queues[name])
  for i,b in enumerate(bg):
   count=(2,4,6,8)[i%4];rank=sorted((-remaining[s],rng.random(),s) for s in names 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=queues[name].pop(0);queues[name].append(obj);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({**obj,'source_um_per_pixel_xy':[.09,.09],'rotation_ccw_degrees':angle,'center_xy':center,'opacity':alpha,'contrast':contrast})
   scenes.append({'id':f'{partition}-{i:04d}','synthetic_partition':partition,'background':b,'instances':items})
  assert not any(remaining.values());num[partition]={'scenes':len(bg),'placements':nplaces,'source_name_strings':len(names)}
 result={'format':'r112-grouped-synthetic-scenes-v1','split_sha256':sha(O/'split.json'),'screen_sha256':sha(O/'similarity-screen.json'),'seed':20261209,'counts':num,'selection':'Each selected background plane used once on its source partition; 2/4/6/8 placements cyclic. Validation uses only source-name strings with at least one unquarantined development source crop in both local partitions. Balance raw source-name strings, cycle source crops, and vary size via source/target XY calibration, angle, alpha, contrast, clustering and frame clipping. All choices fixed before rendering.','labels':'All background pixels unknown; every projected source support and taxon is unverified; overlap and clipping preserved separately; visible anatomy undefined.','limitations':'This is only an internal development control: these images, sources and backgrounds have appeared in earlier work; source slide names and Academy slide filenames are not proof of biological independence. Images from adjacent Z indices share a location and are correlated. No actual optical Z-stack model or independent real performance established. Taxon-string balancing does not resolve synonyms, morphotypes or taxonomy.','scenes':scenes};target.write_text(json.dumps(result,indent=2)+'\n');print('Frozen scene recipes',num)
if __name__=='__main__':main()
