"""Verify paired crop geometry, features, scores and sample model replays."""
import ctypes,hashlib,json,os,signal
from pathlib import Path
import numpy as np,torch
from PIL import Image
from torchvision.models import resnet18
from run_field import embedding
from r112_weak_scenes import transform
R=Path(__file__).resolve().parents[1];S=R/'results/r112/weak-development-v1';O=R/'results/r112/design/species-retention';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')
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);proto=json.loads((O/'protocol.json').read_text());out=json.loads((O/'results.json').read_text());scene_data=json.loads((S/'manifest.json').read_text());prior=R/'results/pilot/ude-adaptation-within-genus/heldout-protocol.json';assert sha(O/'protocol.json')==out['protocol_sha256'] and sha(R/'research/r112_species_retention.py')==out['script_sha256'] and sha(S/'manifest.json')==proto['scene_manifest_sha256'] and sha(prior)==proto['classifier_protocol_sha256'] and sha(CL)==proto['classifier_prototypes_sha256'] and sha(W)==proto['classifier_encoder_sha256'] and sha(O/'features.npz')==out['features_sha256'];labels=json.loads(prior.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==(len(out['records']),3,512) and z['annotation_ids'].tolist()==[r['annotation_id'] for r in out['records']];eligible=set(labels);seen=set();selected=[]
for s in scene_data['records']:
 for j,v in enumerate(s['instances']):
  if v['source_species'] not in eligible or v['annotation_id'] in seen:continue
  seen.add(v['annotation_id']);selected.append((s,j,v))
assert len(selected)==len(proto['records'])==len(out['records'])==59;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};replayed=0;maxdiff=0.
for i,(r,(scene,j,v)) in enumerate(zip(out['records'],selected)):
 assert r['scene_id']==scene['id'] and r['instance_index']==j and r['annotation_id']==v['annotation_id'] and r['source_species']==v['source_species'] and r['source_split']=='development';source=D/v['source_original'];mp=H/v['source_mask_center'];sp=S/scene['image'];arc=S/scene['mask_archive'];assert sha(source)==v['source_original_sha256'] and sha(mp)==v['source_mask_center_sha256'] and sha(sp)==scene['image_sha256'] and sha(arc)==scene['mask_archive_sha256'];raw=Image.open(source).convert('L');mask=np.asarray(Image.open(mp).convert('L'))>0;sx,sy=scene['background_um_per_pixel_xy'];transformed,_,_=transform(np.asarray(raw),mask,sx,sy,v['rotation_ccw_degrees']);h,w=transformed.shape;x,y=v['center_xy'][0]-w//2,v['center_xy'][1]-h//2;x0,y0=max(0,x),max(0,y);x1,y1=min(768,x+w),min(768,y+h);images=[raw,Image.fromarray(transformed[y0-y:y1-y,x0-x:x1-x]),Image.fromarray(np.asarray(Image.open(sp).convert('L'))[y0:y1,x0:x1])];assert r['roi_xyxy']==[x0,y0,x1,y1] and r['in_frame_fraction']==v['in_frame_fraction'] and r['source_rectangle_clipped']==(x0!=x or y0!=y or x1!=x+w or y1!=y+h);m=np.load(arc);shape=tuple(m['support_shape']);supports=np.unpackbits(m['support_bits'])[:np.prod(shape)].reshape(shape).astype(bool);target=supports[j];other=np.logical_or.reduce(np.delete(supports,j,axis=0)) if len(supports)>1 else np.zeros_like(target);overlap=int((target&other).sum());assert r['synthetic_overlap_pixels']==overlap and r['synthetic_overlap_fraction_of_target']==(overlap/int(target.sum()) if target.any() else None)
 for k,(stage,im) in enumerate(zip(('original','transformed','composite'),images)):
  item=r['stages'][stage];path=O/item['image'];assert sha(path)==item['image_sha256'] and np.array_equal(np.asarray(im),np.asarray(Image.open(path).convert('L')));v2=features[i,k];scores=cent@v2;which=int(np.argmax(scores));assert labels[which]==item['prediction'] and item['matches_source_name']==(labels[which]==r['source_species']) and np.allclose(scores,item['scores'],atol=1e-7)
  if i in replay:
   f=embedding(model,im);assert np.allclose(f,v2,atol=1e-7);maxdiff=max(maxdiff,float(np.max(np.abs(f-v2))));replayed+=1
 assert abs(float(features[i,0]@features[i,1])-r['cosine_original_to_transformed'])<1e-7 and abs(float(features[i,1]@features[i,2])-r['cosine_transformed_to_composite'])<1e-7
print(json.dumps({'paired_cases':len(selected),'stages_per_case':3,'neural_embeddings_replayed':replayed,'max_embedding_difference':maxdiff,'checks':'Frozen weights/centroids, first-placement selection, crop geometry, original/synthetic pixels, saved embeddings, scores and selected model replays. Uses shared transformation/embedding code; no species, sample independence or optical realism validated.'},indent=2))
