"""Generate grayscale development-only opaque scenes with reproducible per-instance geometry."""
import hashlib,json,random
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
def extract(s):
 p=R/s['image_path']; a=R/s['annotation_path']; assert sha(p)==s['image_sha256'] and sha(a)==s['annotation_sha256']; data=json.loads(a.read_text()); ann=next(x for x in data['annotations'] if x['image_id']==s['image_id'] and x['id']==s['annotation_id']); rgb=np.asarray(Image.open(p).convert('L').convert('RGB')); mask=np.zeros(rgb.shape[:2],np.uint8)
 for poly in ann['segmentation']: cv2.fillPoly(mask,[np.rint(np.asarray(poly).reshape(-1,2)).astype('int32')],1)
 y,x=np.where(mask); assert len(x)>0; rgb=rgb[y.min():y.max()+1,x.min():x.max()+1]; mask=mask[y.min():y.max()+1,x.min():x.max()+1]; ratio=145/max(mask.shape); dims=(max(1,round(mask.shape[1]*ratio)),max(1,round(mask.shape[0]*ratio))); return cv2.resize(rgb,dims,interpolation=cv2.INTER_AREA),cv2.resize(mask,dims,interpolation=cv2.INTER_NEAREST).astype(bool)
def paste(canvas,crop,mask,center):
 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];canvas[y0:y1,x0:x1][m]=c[m];out[y0:y1,x0:x1]=m
 return out
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/prototype-grayscale';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 main():
 O.mkdir(parents=True,exist_ok=True)
 if (O/'manifest.json').exists():raise FileExistsError('Existing prototype; preserve or explicitly move before rerunning.')
 cv2.setNumThreads(2);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']};crop,mask=extract(spec);objs.append((crop,mask,spec))
 rng=random.Random(20261202);rows=[];conditions=('separated','crossing','cluster','partial')
 for i in range(24):
  cond=conditions[i%len(conditions)];bg=sel['backgrounds'][i%len(sel['backgrounds'])];path=R/bg['path'];assert sha(path)==bg['sha256'];canvas=np.asarray(Image.open(path).convert('L').convert('RGB').resize((512,512),Image.Resampling.LANCZOS)).copy();amount=2 if cond in ('separated','crossing','partial') else 5;choices=rng.sample(range(len(objs)),amount);full=[];instances=[]
  for j,idx in enumerate(choices):
   crop,mask,spec=objs[idx];deg=rng.randrange(0,360,15);size=rng.uniform(.65,1.25);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 cond=='separated':center=[128+256*j,rng.randrange(160,353)]
   elif cond=='crossing':center=[256+rng.randrange(-15,16),256+rng.randrange(-15,16)]
   elif cond=='cluster':center=[256+rng.randrange(-90,91),256+rng.randrange(-90,91)]
   else:center=[rng.choice([0,511]),rng.randrange(100,413)] if j==0 else [rng.randrange(140,373),rng.randrange(140,373)]
   full.append(paste(canvas,rot,rm,center));instances.append({'source':spec,'source_index':idx,'angle_degrees':deg,'scale_from_145px_reference':round(size,8),'center_xy':center,'source_mask_pixels_after_transform':int(rm.sum())})
  visible=[]
  for j,m in enumerate(full):
   later=np.logical_or.reduce(full[j+1:]) if j+1<len(full) else np.zeros_like(m);visible.append(m&~later)
  full=np.stack(full);visible=np.stack(visible)
  for j,entry in enumerate(instances):entry.update({'in_frame_pixels':int(full[j].sum()),'visible_pixels':int(visible[j].sum()),'eligible_visible_at_least_50_pixels':bool(visible[j].sum()>=50)})
  name=f'scene-{i:03d}';ip=O/(name+'.png');ap=O/(name+'.npz');Image.fromarray(canvas).convert('L').save(ip);np.savez_compressed(ap,full_in_frame=full,visible_opaque=visible,background_label_status=np.array('unknown'))
  rows.append({'id':name,'condition':cond,'background':bg,'image':ip.name,'image_sha256':sha(ip),'masks':ap.name,'masks_sha256':sha(ap),'instances':instances})
 manifest={'format':'r112-prototype-v1','purpose':'Development-only renderer and label-schema demonstration; not a training/validation/test split or real performance evidence.','seed':20261202,'generator_sha256':sha(__file__),'selection_sha256':sha(SOURCE),'image_manifest_sha256':sha(MANIFEST),'renderer':'8-bit grayscale source cutouts and grayscale backgrounds, converted before resizing and compositing. Opaque pasted specimens; visible_opaque is full-in-frame minus later pasted silhouettes. Real image background is unannotated and must not be trained as negative. No claim of physical imaging realism.','warning':'Uses 16 previously viewed source images and 8 previously viewed Academy backgrounds; not biologically independent; filenames are not sample identifiers.','scenes':rows}
 (O/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
 sheet=Image.new('RGB',(4*256,3*280),'white');d=ImageDraw.Draw(sheet)
 for j,row in enumerate(rows[:12]):
  img=Image.open(O/row['image']);sheet.paste(img.resize((250,250)),((j%4)*256,(j//4)*280+24));d.text(((j%4)*256+4,(j//4)*280+5),f"{row['id']} · {row['condition']}",fill='#153b36')
 sheet.convert('L').save(O/'contact-sheet.jpg',quality=90);print('Created',len(rows),'development examples from',len(objs),'previously viewed source cutouts and',len(sel['backgrounds']),'backgrounds')
if __name__=='__main__':main()
