"""Paired, uncalibrated transmission-proxy re-render of fixed development scenes."""
import ctypes,hashlib,json,os,signal,time
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from r112_weak_scenes import transform
R=Path(__file__).resolve().parents[1];D=R/'results/r112/species-depth';H=D/'mask-hypotheses';S=R/'results/r112/weak-development-v1';O=R/'results/r112/design/transmission-study'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def render(scene):
 bgpath=R/scene['background']['path'];assert sha(bgpath)==scene['background']['sha256'];background=np.asarray(Image.open(bgpath).convert('L'));canvas=background.astype(np.float32);assert canvas.shape==(768,768);supports=[]
 for x in scene['instances']:
  source=D/x['source_original'];mask=H/x['source_mask_center'];assert sha(source)==x['source_original_sha256'] and sha(mask)==x['source_mask_center_sha256'];im=np.asarray(Image.open(source).convert('L'));m=np.asarray(Image.open(mask).convert('L'))>0;sx,sy=scene['background_um_per_pixel_xy'];trans,ms,dims=transform(im,m,sx,sy,x['rotation_ccw_degrees']);assert dims==x['resampled_dimensions_px'];h,w=ms.shape;cx,cy=x['center_xy'];x0,y0=max(0,cx-w//2),max(0,cy-h//2);x1,y1=min(768,cx-w//2+w),min(768,cy-h//2+h);placed=np.zeros(canvas.shape,bool)
  if x1>x0 and y1>y0:
   xx=x0-(cx-w//2);yy=y0-(cy-h//2);weak=ms[yy:yy+y1-y0,xx:xx+x1-x0];pixels=trans[yy:yy+y1-y0,xx:xx+x1-x0].astype(np.float32);ratio=np.clip(np.maximum(pixels,1.)/max(float(x['source_background_median']),1.),.05,2.);factor=1.-x['opacity']+x['opacity']*np.power(ratio,x['contrast']);dest=canvas[y0:y1,x0:x1];dest[weak]*=factor[weak];placed[y0:y1,x0:x1]=weak
  assert int(placed.sum())==x['in_frame_support_pixels'];supports.append(placed)
 assert len(supports)==len(scene['instances']);return np.rint(np.clip(canvas,0,255)).astype(np.uint8),background,np.stack(supports),canvas
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
 scenes=json.loads((S/'manifest.json').read_text())['records'];records=[];start=time.monotonic()
 for i,s in enumerate(scenes):
  img,bg,masks,raw=render(s);old=S/s['image'];arc=S/s['mask_archive'];assert sha(old)==s['image_sha256'] and sha(arc)==s['mask_archive_sha256'];z=np.load(arc);shape=tuple(z['support_shape']);stored=np.unpackbits(z['support_bits'])[:np.prod(shape)].reshape(shape).astype(bool);assert np.array_equal(masks,stored);name=s['id']+'-transmission.png';Image.fromarray(img).save(O/name);orig=np.asarray(Image.open(old).convert('L'));support=masks.any(0);records.append({'scene_id':s['id'],'image':name,'image_sha256':sha(O/name),'baseline_image_sha256':s['image_sha256'],'supports_sha256':s['mask_archive_sha256'],'changed_pixels_vs_baseline':int(np.count_nonzero(img!=orig)),'new_boundary_values_vs_background_in_support':int(np.count_nonzero(support&((img==0)|(img==255))&((bg!=0)&(bg!=255)))),'above_255_before_clipping':int((raw>255).sum()),'below_zero_before_clipping':int((raw<0).sum())})
  if (i+1)%50==0:print(i+1,'/',len(scenes),'elapsed',round(time.monotonic()-start,1),flush=True)
 out={'format':'r112-transmission-render-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'warning':p['limits'],'records':records};(O/'manifest.json').write_text(json.dumps(out,indent=2)+'\n');print('rendered',len(records))
if __name__=='__main__':main()
