"""Render the frozen group-separated *development* comparison scenes."""
import ctypes,hashlib,json,os,signal,time
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from r112_broad_scene_render import render
R=Path(__file__).resolve().parents[1];O=R/'results/r112/grouped-synthetic';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
 if parent!=os.getppid():raise RuntimeError('launcher exited')
 cv2.setNumThreads(2);p=json.loads((O/'scene-protocol.json').read_text());assert not (O/'manifest.json').exists() and p['split_sha256']==sha(O/'split.json') and p['screen_sha256']==sha(O/'similarity-screen.json');rows=[];start=time.monotonic()
 for i,s in enumerate(p['scenes']):
  part=s['synthetic_partition'];assert s['background']['synthetic_partition']==part and all(x['synthetic_partition']==part for x in s['instances']);img,masks,items=render(s);name=s['id'];ip=O/(name+'.png');mp=O/(name+'.npz');Image.fromarray(img).save(ip);np.savez_compressed(mp,support_bits=np.packbits(masks.ravel()),support_shape=np.array(masks.shape),background_label_status=np.array('unknown'),transparent_visibility_status=np.array('undefined'));pairs=sum(bool((masks[a]&masks[b]).any()) for a in range(len(masks)) for b in range(a+1,len(masks)));rows.append({'id':name,'split':'development_only','synthetic_partition':part,'background':s['background'],'background_um_per_pixel_xy':s['background']['um_per_pixel_xy'],'image':ip.name,'image_sha256':sha(ip),'mask_archive':mp.name,'mask_archive_sha256':sha(mp),'overlap_pairs':pairs,'instances':items})
  if (i+1)%40==0:print(i+1,'/',len(p['scenes']),'elapsed',round(time.monotonic()-start,1),flush=True)
 result={'format':'r112-grouped-synthetic-scenes-v1','protocol_sha256':sha(O/'scene-protocol.json'),'generator_sha256':sha(__file__),'warning':p['labels']+' '+p['limitations'],'records':rows};(O/'manifest.json').write_text(json.dumps(result,indent=2)+'\n');print('rendered',len(rows),'scenes')
if __name__=='__main__':main()
