"""Reconstruct paired gain variants, support masks and incremental renderer diagnostics."""
import ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from r112_weak_scenes import transform,place
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/contrast-study'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
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());out=json.loads((O/'results.json').read_text());src=json.loads((S/'manifest.json').read_text())['records'][:32];assert sha(S/'manifest.json')==p['source_manifest_sha256'] and sha(S/'protocol.json')==p['source_protocol_sha256'] and sha(O/'protocol.json')==out['protocol_sha256'] and sha(R/'research/r112_contrast_study.py')==out['script_sha256'] and [r['scene'] for r in out['records']]==[r['id'] for r in src];counts=0
for row,original in zip(out['records'],src):
 assert row['background']==original['background'];bg=R/row['background']['path'];assert sha(bg)==row['background']['sha256'];mp=S/row['baseline_mask_archive'];assert sha(mp)==row['baseline_mask_sha256']==original['mask_archive_sha256'];z=np.load(mp);shape=tuple(z['support_shape']);supports=np.unpackbits(z['support_bits'])[:np.prod(shape)].reshape(shape).astype(bool);sx,sy=original['background_um_per_pixel_xy']
 for gain in p['gains']:
  canvas=np.asarray(Image.open(bg).convert('L')).copy();variant=row['variants'][str(int(gain))];assert len(variant['placements'])==len(original['instances'])
  for k,(v,x) in enumerate(zip(variant['placements'],original['instances'])):
   source=D/x['source_original'];maskpath=H/x['source_mask_center'];assert sha(source)==x['source_original_sha256'] and sha(maskpath)==x['source_mask_center_sha256'];im=np.asarray(Image.open(source).convert('L'));mask=np.asarray(Image.open(maskpath).convert('L'))>0;crop,mask,wh=transform(im,mask,sx,sy,x['rotation_ccw_degrees']);assert wh==x['resampled_dimensions_px'];before=canvas.copy();support=place(canvas,crop,mask,x['center_xy'],x['opacity'],x['contrast']*gain,x['source_background_median']);assert np.array_equal(support,supports[k]);diff=np.abs(canvas.astype('int16')-before.astype('int16'));values=diff[support];edge=((canvas==0)|(canvas==255))&~((before==0)|(before==255));assert v['annotation_id']==x['annotation_id'] and v['support_pixels']==int(support.sum()) and v['mean_absolute_change']==(float(values.mean()) if len(values) else None) and v['new_boundary_pixels']==int((edge&support).sum()) and v['changed_pixels']==int((diff[support]>0).sum());counts+=1
  path=O/variant['image'];assert sha(path)==variant['sha256'] and np.array_equal(canvas,np.asarray(Image.open(path).convert('L')))
  if gain==1.:assert np.array_equal(canvas,np.asarray(Image.open(S/original['image']).convert('L')))
print(json.dumps({'scenes':len(src),'gains':p['gains'],'placement_variants':counts,'checks':'Rebuilt every image, source/support hash, v1 equality and per-placement incremental statistics using the same transformation and placement helpers; no biological accuracy or physical optical validation.'},indent=2))
