"""Render isolated projected supports without marking Academy background negative."""
import ctypes,json,os,random,signal,time
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset
from r112_scaleup_scene_render import layer,SIZE
from r112_scaleup_synthetic_compare import sha
from r112_weak_scenes import transform
R=Path(__file__).resolve().parents[1];O=R/'results/r112/scaleup-separated-scenes'
def project(mask,center):
 h,w=mask.shape;x=center[0]-w//2;y=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:out[y0:y1,x0:x1]=mask[y0-y:y1-y,x0-x:x1-x]
 return out

def render(scene,dataset,cache):
 b=scene['background'];path=R/b['path']
 if str(path) not in cache:assert sha(path)==b['sha256'];cache[str(path)]=np.asarray(Image.open(path).convert('L'))
 background=cache[str(path)];assert background.shape==(SIZE,SIZE);sx,sy=b['um_per_pixel_xy'];prepared=[]
 for row in scene['instances']:
  x=dataset[row['training_index']];assert x['annotation_id']==row['annotation_id'] and x['source_name']==row['source_name'] and x['source_um_per_pixel_xy']==[.09,.09];src=np.asarray(x['image']);mask=x['weak_mask_proposals'][0];median=float(np.median(src[~mask])) if (~mask).any() else float(np.median(src));pix,ms,dims=transform(src,mask,sx,sy,row['rotation_ccw_degrees']);assert ms.any();prepared.append((row,x,pix,ms,dims,median))
 rng=random.Random(scene['placement_seed']);total_attempts=0;layout=None
 for retry in range(30):
  occupied=np.zeros((SIZE,SIZE),bool);chosen=[]
  for row,x,pix,ms,dims,median in prepared:
   full=int(ms.sum());accept=None
   for attempt in range(100):
    total_attempts+=1
    if row['prefer_edge']:center=[rng.choice([0,SIZE-1]),rng.randrange(SIZE)]
    else:center=[rng.randrange(SIZE),rng.randrange(SIZE)]
    support=project(ms,center);area=int(support.sum())
    if area>=.15*full and not (support&occupied).any():accept=(center,support,attempt+1);break
   if accept is None:break
   center,support,_=accept;occupied|=support;chosen.append(accept)
  if len(chosen)==len(prepared):layout=chosen;break
 if layout is None:raise RuntimeError(f"Could not create separated layout for {scene['id']} after {total_attempts} proposals")
 canvas=background.astype(np.float32).copy();supports=[];items=[]
 for (row,x,pix,ms,dims,median),(center,expect,attempts) in zip(prepared,layout):
  actual=layer(canvas,pix,ms,center,row['opacity'],row['contrast_exponent'],median);assert np.array_equal(actual,expect);full=int(ms.sum());area=int(actual.sum());supports.append(actual);items.append({**row,'center_xy':center,'placement_attempts_in_final_retry':attempts,'source_slide':x['source_slide'],'mask_triage':x['mask_triage'],'source_um_per_pixel_xy':x['source_um_per_pixel_xy'],'source_background_median':median,'resampled_dimensions_px':dims,'transformed_support_pixels':full,'in_frame_support_pixels':area,'in_frame_fraction':area/full,'mask_status':'unverified projected model proposal','visible_support_status':'undefined','background_status':'unknown, may contain diatoms'})
 return np.rint(np.clip(canvas,0,255)).astype('uint8'),np.stack(supports),items,background,{'scene_retry':retry,'candidate_attempts_total':total_attempts}

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/'protocol.json').read_text());assert not (O/'manifest.json').exists()
 for f,h in p['inputs_sha256'].items():assert sha(R/f)==h,f
 data=UDEScaleupDataset('training',include_unverified_masks=True);cache={};records=[];start=time.monotonic()
 for i,s in enumerate(p['scenes']):
  img,masks,items,bg,placement=render(s,data,cache);ip=O/(s['id']+'.png');mp=O/(s['id']+'.npz');Image.fromarray(img).save(ip);np.savez_compressed(mp,support_bits=np.packbits(masks.ravel()),support_shape=np.array(masks.shape,dtype=np.int32),background_label_status=np.array('unknown'),visible_support_status=np.array('undefined'));assert all(not (masks[a]&masks[b]).any() for a in range(len(masks)) for b in range(a+1,len(masks)));records.append({'id':s['id'],'image':ip.name,'image_sha256':sha(ip),'mask_archive':mp.name,'mask_archive_sha256':sha(mp),'background':s['background'],'support_overlap_pairs':0,'changed_pixels_vs_background':int(np.count_nonzero(img!=bg)),'placement':placement,'instances':items});(O/'progress.json').write_text(json.dumps({'completed':i+1,'total':len(p['scenes']),'note':'Checkpoint only, not proof of a running process.'},indent=2)+'\n')
  if (i+1)%25==0:print('scenes',i+1,'/',len(p['scenes']),'seconds',round(time.monotonic()-start),flush=True)
 result={'format':p['format'],'protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'warning':p['labels']+' '+p['limitations'],'records':records};(O/'manifest.json').write_text(json.dumps(result,indent=2)+'\n');print('complete',len(records),'scenes',sum(len(x['instances']) for x in records),'instances',flush=True)
if __name__=='__main__':main()
