"""Generate source-calibrated weak-label synthetic development scenes."""
import collections,csv,ctypes,hashlib,json,os,random,signal,time
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];D=R/'results/r112/breadth-depth';H=D/'mask-hypotheses';O=R/'results/r112/weak-breadth-depth-v1';B=R/'results/l78/training-selection.json';I=R/'results/scan-inventory.csv';SIZE=768
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(1048576),b''):h.update(b)
 return h.hexdigest()
def transform(im,mask,sx,sy,angle):
 h,w=im.shape;tw=max(1,round(w*.09/sx));th=max(1,round(h*.09/sy));image=Image.fromarray(cv2.resize(im,(tw,th),interpolation=cv2.INTER_AREA));support=Image.fromarray(cv2.resize(mask.astype('uint8')*255,(tw,th),interpolation=cv2.INTER_NEAREST));return np.asarray(image.rotate(angle,resample=Image.Resampling.BICUBIC,expand=True)),np.asarray(support.rotate(angle,resample=Image.Resampling.NEAREST,expand=True))>0,[tw,th]
def place(canvas,im,mask,center,alpha,contrast,source_median):
 h,w=mask.shape;x,y=center[0]-w//2,center[1]-h//2;x0=max(0,x);y0=max(0,y);x1=min(SIZE,x+w);y1=min(SIZE,y+h);out=np.zeros((SIZE,SIZE),bool)
 if x1>x0 and y1>y0:
  m=mask[y0-y:y1-y,x0-x:x1-x];obj=im[y0-y:y1-y,x0-x:x1-x].astype('float32');dest=canvas[y0:y1,x0:x1];delta=(obj-source_median)*alpha*contrast;dest[m]=np.rint(dest[m].astype('float32')+delta[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);proto=json.loads((O/'protocol.json').read_text());assert not (O/'manifest.json').exists();assert sha(D/'development-assets.json')==proto['source_assets_sha256'] and sha(H/'results.json')==proto['mask_hypotheses_sha256'] and sha(B)==proto['background_selection_sha256'] and sha(I)==proto['scan_inventory_sha256'];dev=json.loads((D/'development-assets.json').read_text())['records'];hyp={r['annotation_id']:r for r in json.loads((H/'results.json').read_text())['records']};pool=collections.defaultdict(list)
 for r in dev:
  q=hyp[r['annotation_id']]
  if q['triage']!='consistent-unverified':continue
  src=D/r['source_crop'];mp=H/q['masks']['center']['file'];assert sha(src)==r['source_sha256'] and sha(mp)==q['masks']['center']['sha256'];im=np.asarray(Image.open(src).convert('L'));mask=np.asarray(Image.open(mp).convert('L'))>0;assert im.shape==mask.shape and mask.any() and (~mask).any();pool[r['source_species']].append({'record':r,'hypothesis':q,'image':im,'mask':mask,'median':float(np.median(im[~mask]))})
 assert sum(map(len,pool.values()))==112 and len(pool)==20
 backgrounds=json.loads(B.read_text())['backgrounds'];inventory={x['filename']:x for x in csv.DictReader(I.open())};assert len(backgrounds)==8
 for bg in backgrounds:
  scan=R/'scans'/bg['slide'];assert scan.stat().st_size>=1_000_000_000 and scan.stat().st_size==bg['slide_bytes'] and int(inventory[bg['slide']]['bytes'])==bg['slide_bytes'];assert sha(R/bg['path'])==bg['sha256'] and Image.open(R/bg['path']).size==(SIZE,SIZE)
 rng=random.Random(proto['seed']);remaining={s:40 for s in sorted(pool)};slots=[]
 for scene_index in range(proto['scene_count']):
  n=(2,4,6,8)[scene_index%4]; rank=sorted(((-remaining[s],rng.random(),s) for s in remaining if remaining[s]>0)); assert len(rank)>=n
  for _,_,s in rank[:n]:slots.append(s);remaining[s]-=1
 assert not any(remaining.values());pos=0;out=[];start=time.monotonic()
 for scene in range(proto['scene_count']):
  bg=backgrounds[scene%len(backgrounds)];meta=inventory[bg['slide']];sx,sy=float(meta['um_per_pixel_x']),float(meta['um_per_pixel_y']);canvas=np.asarray(Image.open(R/bg['path']).convert('L')).copy();count=(2,4,6,8)[scene%4];supports=[];items=[];used=set();anchor=[rng.randrange(140,628),rng.randrange(140,628)]
  for j in range(count):
   species=slots[pos];pos+=1;available=[x for x in pool[species] if x['record']['annotation_id'] not in used];assert available;source=rng.choice(available);r=source['record'];q=source['hypothesis'];used.add(r['annotation_id']);angle=rng.randrange(0,360,15);alpha=round(rng.uniform(.30,.85),8);contrast=round(rng.uniform(.65,1.35),8);image,mask,scaled=transform(source['image'],source['mask'],sx,sy,angle)
   if j==0 and scene%4==0:center=[rng.choice([0,SIZE-1]),rng.randrange(SIZE)]
   elif j<3:center=[int(np.clip(anchor[0]+rng.randrange(-70,71),0,SIZE-1)),int(np.clip(anchor[1]+rng.randrange(-70,71),0,SIZE-1))]
   else:center=[rng.randrange(SIZE),rng.randrange(SIZE)]
   support=place(canvas,image,mask,center,alpha,contrast,source['median']);supports.append(support);total=int(mask.sum());items.append({'annotation_id':r['annotation_id'],'source_species':species,'source_genus':r['source_genus'],'source_slide_group':r['source_slide_group'],'source_original':r['source_crop'],'source_original_sha256':r['source_sha256'],'source_mask_center':q['masks']['center']['file'],'source_mask_center_sha256':q['masks']['center']['sha256'],'alternate_masks':{k:q['masks'][k] for k in ('minus','plus')},'source_um_per_pixel_xy':[.09,.09],'target_um_per_pixel_xy':[sx,sy],'resampled_dimensions_px':scaled,'rotation_ccw_degrees':angle,'center_xy':center,'opacity':alpha,'contrast':contrast,'source_background_median':source['median'],'transformed_support_pixels':total,'in_frame_support_pixels':int(support.sum()),'in_frame_fraction':int(support.sum())/total if total else None,'taxon_status':'unverified source metadata','mask_status':'unverified model hypothesis','transparent_visibility':'undefined'})
  masks=np.stack(supports);name=f'scene-{scene:04d}';ip=O/f'{name}.png';mp=O/f'{name}.npz';Image.fromarray(canvas).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(count) for b in range(a+1,count));out.append({'id':name,'split':'development_only','background':bg,'background_um_per_pixel_xy':[sx,sy],'image':ip.name,'image_sha256':sha(ip),'mask_archive':mp.name,'mask_archive_sha256':sha(mp),'overlap_pairs':pairs,'instances':items});(O/'progress.json').write_text(json.dumps({'completed_scenes':scene+1,'total_scenes':proto['scene_count'],'note':'Last saved checkpoint; this file alone does not prove process liveness.'},indent=2)+'\n')
  if (scene+1)%25==0:print(scene+1,'/',proto['scene_count'],'elapsed',round(time.monotonic()-start,1),flush=True)
 assert pos==800;result={'format':'r112-weak-breadth-depth-v1','protocol_sha256':sha(O/'protocol.json'),'generator_sha256':sha(__file__),'warning':proto['labels'],'records':out};(O/'manifest.json').write_text(json.dumps(result,indent=2)+'\n');sheet=Image.new('L',(4*256,3*280),'white');draw=ImageDraw.Draw(sheet)
 for j,row in enumerate(out[:12]):sheet.paste(Image.open(O/row['image']).resize((250,250)),((j%4)*256,(j//4)*280+24));draw.text(((j%4)*256+4,(j//4)*280+5),f"{row['id']} · {len(row['instances'])} weak supports",fill=35)
 sheet.save(O/'contact-sheet.jpg',quality=90);print('done',len(out),'scenes',pos,'placements')
if __name__=='__main__':main()
