"""Rebuild every blending scene, ring median and classifier crop; replay selected features."""
import ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from torchvision.models import resnet18
from run_field import embedding
from r112_weak_scenes import transform,place
from r112_species_blends import alpha_place
R=Path(__file__).resolve().parents[1];S=R/'results/r112/weak-development-v1';P=R/'results/r112/design/species-retention-corrected';O=R/'results/r112/design/species-blend-study';D=R/'results/r112/species-depth';H=D/'mask-hypotheses';CL=R/'results/pilot/ude-adaptation-within-genus/centroid-pilot/prototypes.npz';W=Path('/tmp/resnet18-f37072fd.pth');T=R/'results/pilot/ude-adaptation-within-genus/heldout-protocol.json'
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()
parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
if parent!=os.getppid():raise RuntimeError('launcher exited')
torch.set_num_threads(2);cv2.setNumThreads(2);p=json.loads((O/'protocol.json').read_text());out=json.loads((O/'results.json').read_text());prior=json.loads((P/'results.json').read_text());scenes={s['id']:s for s in json.loads((S/'manifest.json').read_text())['records']};assert sha(O/'protocol.json')==out['protocol_sha256'] and sha(R/'research/r112_species_blends.py')==out['script_sha256'] and sha(P/'results.json')==p['prior_results_sha256'] and sha(S/'manifest.json')==p['weak_scenes_sha256'] and sha(CL)==p['classifier_prototypes_sha256'] and sha(W)==p['classifier_encoder_sha256'] and sha(T)==p['classifier_protocol_sha256'] and sha(O/'features.npz')==out['features_sha256'];assert [x['annotation_id'] for x in out['records']]==[x['annotation_id'] for x in prior['records']];labels=json.loads(T.read_text())['label_order'];assert labels==out['labels'];cent=np.load(CL)['generic'];z=np.load(O/'features.npz');features=z['features'];assert features.shape==(59,3,512) and z['annotation_ids'].tolist()==[x['annotation_id'] for x in prior['records']];cache={}
for sid,variants in out['scene_variants'].items():
 scene=scenes[sid];bg=R/scene['background']['path'];assert sha(bg)==scene['background']['sha256'];background=np.asarray(Image.open(bg).convert('L'));sx,sy=scene['background_um_per_pixel_xy'];arc=S/scene['mask_archive'];assert sha(arc)==scene['mask_archive_sha256'];z=np.load(arc);shape=tuple(z['support_shape']);supports=np.unpackbits(z['support_bits'])[:np.prod(shape)].reshape(shape).astype(bool);cache[sid]={'background':background,'supports':supports,'variants':{}}
 for mode in p['modes']:
  canvas=background.copy();medians=[]
  for j,x in enumerate(scene['instances']):
   sp=D/x['source_original'];mp=H/x['source_mask_center'];assert sha(sp)==x['source_original_sha256'] and sha(mp)==x['source_mask_center_sha256'];im=np.asarray(Image.open(sp).convert('L'));mask=np.asarray(Image.open(mp).convert('L'))>0;crop,ms,dims=transform(im,mask,sx,sy,x['rotation_ccw_degrees']);assert dims==x['resampled_dimensions_px']
   if mode=='additive_v1':support=place(canvas,crop,ms,x['center_xy'],x['opacity'],x['contrast'],x['source_background_median']);median=None
   else:support,median=alpha_place(canvas,crop,ms,x['center_xy'],x['opacity'],x['contrast'],x['source_background_median'],mode)
   assert np.array_equal(support,supports[j]);medians.append(median)
  path=O/variants[mode]['image'];assert medians==variants[mode]['local_medians'] and sha(path)==variants[mode]['sha256'] and np.array_equal(canvas,np.asarray(Image.open(path).convert('L')));cache[sid]['variants'][mode]=canvas
  if mode=='additive_v1':assert np.array_equal(canvas,np.asarray(Image.open(S/scene['image']).convert('L')))
model=resnet18(weights=None);model.load_state_dict(torch.load(W,map_location='cpu',weights_only=True));model.fc=torch.nn.Identity();model.eval();replay={0,10,20,30,40,50};n=0;maxdiff=0.
for i,(r,old) in enumerate(zip(out['records'],prior['records'])):
 assert r['annotation_id']==old['annotation_id'] and r['scene_id']==old['scene_id'] and r['source_species']==old['source_species'] and r['roi_xyxy']==old['roi_xyxy'] and r['instance_index']==old['instance_index'];data=cache[r['scene_id']];target=data['supports'][r['instance_index']];background=data['background'];x0,y0,x1,y1=r['roi_xyxy']
 for j,mode in enumerate(p['modes']):
  v=r['variants'][mode];canvas=data['variants'][mode];crop=Image.fromarray(canvas[y0:y1,x0:x1]);assert sha(O/v['image'])==v['image_sha256'] and np.array_equal(np.asarray(crop),np.asarray(Image.open(O/v['image']).convert('L')));scores=cent@features[i,j];name=labels[int(np.argmax(scores))];extreme=((canvas==0)|(canvas==255))&~((background==0)|(background==255));assert np.allclose(scores,v['scores'],atol=1e-7) and name==v['prediction'] and v['matches_source_name']==(name==r['source_species']) and v['target_support_pixels']==int(target.sum()) and v['new_boundary_pixels_within_target_support']==int((extreme&target).sum())
  if mode=='additive_v1':assert name==old['stages']['composite']['prediction'] and v['image_sha256']==old['stages']['composite']['image_sha256']
  if i in replay:
   f=embedding(model,crop);assert np.allclose(f,features[i,j],atol=1e-7);maxdiff=max(maxdiff,float(np.max(np.abs(f-features[i,j]))));n+=1
print(json.dumps({'cases':len(out['records']),'unique_scenes':len(cache),'full_scene_variants':len(cache)*3,'classifier_embeddings_replayed':n,'max_embedding_difference':maxdiff,'checks':'Reconstructed all outputs, support masks, local ring medians, classifier scores and boundary proxies; replayed selected embeddings. Shares rendering and embedding code; source/optical realism and biological correctness remain unverified.'},indent=2))
