"""Development-only crowded translucent scenes; projected supports can overlap."""
import ctypes,hashlib,json,os,random,signal
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
from r112_grayscale import extract
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/broader';SOURCE=R/'results/l78/training-selection.json';MANIFEST=R/'results/l78/training-image-manifest.json'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def place(canvas,crop,mask,center,alpha,contrast):
 h,w=mask.shape;x,y=center[0]-w//2,center[1]-h//2;x0=max(0,x);y0=max(0,y);x1=min(512,x+w);y1=min(512,y+h);out=np.zeros((512,512),bool)
 if x1>x0 and y1>y0:
  m=mask[y0-y:y1-y,x0-x:x1-x];c=crop[y0-y:y1-y,x0-x:x1-x].astype('float32');roi=canvas[y0:y1,x0:x1];c=np.clip((c-128)*contrast+128,0,255);roi[m]=np.rint((1-alpha)*roi[m].astype('float32')+alpha*c[m]).clip(0,255).astype('uint8');out[y0:y1,x0:x1]=m
 return out
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);O.mkdir(parents=True,exist_ok=True)
 if (O/'manifest.json').exists():raise FileExistsError('Existing run; use a new output location.')
 sel=json.loads(SOURCE.read_text());imgs=json.loads(MANIFEST.read_text())['records'];objs=[]
 for a,b in zip(sel['training_sources'],imgs):
  spec={'image_path':b['path'],'image_sha256':b['sha256'],'annotation_path':'datasets/r84-khanom/'+a['coco_file'],'annotation_sha256':a['coco_sha256'],'image_id':a['image_id'],'annotation_id':a['annotation_id'],'source_genus_folder':a['species_folder'],'species':None,'source_license':'CC BY 4.0','taxon_label_status':'folder label only, species unknown'};crop,mask=extract(spec);objs.append((crop[:,:,0],mask,spec))
 # R91 references were previously examined; they are development sources only.
 audit=json.loads((R/'results/r91/metadata-audit.json').read_text()); observed={str(x['id']) for x in json.loads((R/'results/r91/results.json').read_text())['records']}; images={str(x['id']):x for x in json.loads((R/'results/r91/image-manifest.json').read_text())['records']}
 for record in audit['records']:
  ident=str(record['id'])
  if ident not in observed:continue
  assert record['status']=='structural_match' and ident in images
  ip=R/images[ident]['path'];mp=R/'datasets/r91-gunduz/masks'/f'{ident}.png';xp=R/'datasets/r91-gunduz/xml'/f'{ident}.xml'
  assert sha(ip)==images[ident]['sha256'] and sha(mp)==record['mask_sha256'] and sha(xp)==record['xml_sha256']
  image=np.asarray(Image.open(ip).convert('L'));binary=np.asarray(Image.open(mp).convert('L'))>0;_,labels=cv2.connectedComponents(binary.astype('uint8'),connectivity=8)
  for item in record['instances']:
   m=labels==item['component_label'];assert int(m.sum())==item['area'];obj=record['objects'][item['box_index']];yy,xx=np.where(m);mask=m[yy.min():yy.max()+1,xx.min():xx.max()+1];crop=image[yy.min():yy.max()+1,xx.min():xx.max()+1];ratio=145/max(mask.shape);size=(max(1,round(mask.shape[1]*ratio)),max(1,round(mask.shape[0]*ratio)));mask=cv2.resize(mask.astype('uint8'),size,interpolation=cv2.INTER_NEAREST).astype(bool);crop=cv2.resize(crop,size,interpolation=cv2.INTER_AREA);name=obj['name'];spec={'image_path':str(ip.relative_to(R)),'image_sha256':sha(ip),'mask_path':str(mp.relative_to(R)),'mask_sha256':sha(mp),'xml_path':str(xp.relative_to(R)),'xml_sha256':sha(xp),'component_label':item['component_label'],'box_index':item['box_index'],'source_genus_folder':name.split()[0].lower(),'species':name,'taxon_label_status':'source label only, not independently confirmed','mask_status':'binary component matched to nonintersecting source box, not expert-confirmed instance','source_license':'CC BY-NC-SA 4.0'};objs.append((crop,mask,spec))
 # Add eligible earlier Gündüz component/box matches; all development-only.
 extra=json.loads((R/'results/r112/design/source-audit/r80-audit.json').read_text())
 for record in extra['records']:
  if record['structural']['status']!='structural_match' or record['previous_similarity_quarantine']:continue
  ip=R/record['image'];mp=R/record['mask'];xp=R/record['xml'];assert sha(ip)==record['image_sha256'] and sha(mp)==record['mask_sha256'] and sha(xp)==record['xml_sha256'];image=np.asarray(Image.open(ip).convert('L'));binary=np.asarray(Image.open(mp).convert('L'))>0;_,labels=cv2.connectedComponents(binary.astype('uint8'),connectivity=8)
  for item in record['structural']['instances']:
   m=labels==item['component_label'];assert int(m.sum())==item['area'];obj=record['objects'][item['box_index']];yy,xx=np.where(m);mask=m[yy.min():yy.max()+1,xx.min():xx.max()+1];crop=image[yy.min():yy.max()+1,xx.min():xx.max()+1];ratio=145/max(mask.shape);size=(max(1,round(mask.shape[1]*ratio)),max(1,round(mask.shape[0]*ratio)));mask=cv2.resize(mask.astype('uint8'),size,interpolation=cv2.INTER_NEAREST).astype(bool);crop=cv2.resize(crop,size,interpolation=cv2.INTER_AREA);name=obj['name'];spec={'image_path':record['image'],'image_sha256':record['image_sha256'],'mask_path':record['mask'],'mask_sha256':record['mask_sha256'],'xml_path':record['xml'],'xml_sha256':record['xml_sha256'],'component_label':item['component_label'],'box_index':item['box_index'],'source_genus_folder':name.split()[0].lower(),'species':name,'taxon_label_status':'source label only, not independently confirmed','mask_status':'binary component matched to nonintersecting source box, not expert-confirmed instance','source_license':'CC BY-NC-SA 4.0'};objs.append((crop,mask,spec))
 rng=random.Random(20261203);rows=[]
 for i in range(32):
  count=(4,8,12,18)[i%4];bg=sel['backgrounds'][i%len(sel['backgrounds'])];path=R/bg['path'];assert sha(path)==bg['sha256'];canvas=np.asarray(Image.open(path).convert('L').resize((512,512),Image.Resampling.LANCZOS)).copy();full=[];instances=[];cluster=[rng.randrange(100,413),rng.randrange(100,413)]
  choices=rng.sample(range(len(objs)),count)
  for j in range(count):
   idx=choices[j];crop,mask,spec=objs[idx];deg=rng.randrange(0,360,15);size=rng.uniform(.35,1.65);alpha=rng.uniform(.25,.9);contrast=rng.uniform(.65,1.4);dims=(max(2,round(crop.shape[1]*size)),max(2,round(crop.shape[0]*size)));im=Image.fromarray(crop).resize(dims,Image.Resampling.LANCZOS).rotate(deg,resample=Image.Resampling.BICUBIC,expand=True);ma=Image.fromarray(mask.astype('uint8')*255).resize(dims,Image.Resampling.NEAREST).rotate(deg,resample=Image.Resampling.NEAREST,expand=True);rot=np.asarray(im);rm=np.asarray(ma)>0
   if j%3==0:center=[int(np.clip(cluster[0]+rng.randrange(-60,61),0,511)),int(np.clip(cluster[1]+rng.randrange(-60,61),0,511))]
   elif j%7==0:center=[rng.choice([0,511]),rng.randrange(512)]
   else:center=[rng.randrange(512),rng.randrange(512)]
   support=place(canvas,rot,rm,center,alpha,contrast);full.append(support);instances.append({'source':spec,'source_index':idx,'angle_degrees':deg,'scale_from_145px_reference':round(size,8),'center_xy':center,'opacity':round(alpha,8),'contrast':round(contrast,8),'mask_pixels_after_transform':int(rm.sum()),'in_frame_pixels':int(support.sum())})
  stack=np.stack(full);coverage=np.sum(stack,axis=0);overlap=int((coverage>=2).sum());pair_count=sum(bool((stack[a]&stack[b]).any()) for a in range(count) for b in range(a+1,count));name=f'scene-{i:03d}';ip=O/(name+'.png');ap=O/(name+'.npz');Image.fromarray(canvas).save(ip);np.savez_compressed(ap,projected_supports=stack,background_label_status=np.array('unknown'),transparency_visibility_status=np.array('not_defined'));rows.append({'id':name,'requested_count':count,'background':bg,'image':ip.name,'image_sha256':sha(ip),'masks':ap.name,'masks_sha256':sha(ap),'overlap_pixels':overlap,'intersecting_pairs':pair_count,'instances':instances})
 manifest={'format':'r112-translucent-v1','purpose':'Development-only alpha-compositing and per-instance label demonstration; not validated optical simulation, benchmark or training set.','seed':20261203,'generator_sha256':sha(__file__),'selection_sha256':sha(SOURCE),'image_manifest_sha256':sha(MANIFEST),'r80_added_audit_sha256':sha(R/'results/r112/design/source-audit/r80-audit.json'),'r91_audit_sha256':sha(R/'results/r91/metadata-audit.json'),'r91_results_sha256':sha(R/'results/r91/results.json'),'r91_image_manifest_sha256':sha(R/'results/r91/image-manifest.json'),'rendering':'Sequential alpha blend I=(1-alpha)*I+alpha*adjusted_cutout within transformed source support; contrast about grayscale 128, clamp after each layer. Projected supports retained as separate overlapping masks, not biological visible outlines; final image may not contain distinguishable structure in all support pixels.','warning':'Original background contains unlabeled possible specimens, including under inserted cutouts; background unknown is not negative. Gunduz source taxon names and structural component masks are not independently confirmed. Source images/backgrounds reused and sample independence unknown. Mixed-source derivatives include CC BY-NC-SA 4.0 material; inspect all rights before use. Alpha blending is not a physical microscope model.','scenes':rows}
 (O/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n');sheet=Image.new('L',(4*256,3*280),'white');d=ImageDraw.Draw(sheet)
 for j,row in enumerate(rows[:12]):
  sheet.paste(Image.open(O/row['image']).resize((250,250)),((j%4)*256,(j//4)*280+24));d.text(((j%4)*256+4,(j//4)*280+5),f"{row['id']} · {row['requested_count']} inserted",fill=35)
 sheet.save(O/'contact-sheet.jpg',quality=90);print('Generated',len(rows),'scenes;',sum(r['requested_count'] for r in rows),'placements;',sum(r['intersecting_pairs'] for r in rows),'overlapping pairs')
if __name__=='__main__':main()
