"""Verify all candidate geometry, then replay four triple-prompt cases."""
import ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics.models.sam import Predictor
from r112_mask_hypotheses import points_for
R=Path(__file__).resolve().parents[1];D=R/'results/r112/species-depth';O=D/'mask-hypotheses';NAMES=('center','minus','plus')
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);protocol=json.loads((O/'protocol.json').read_text());data=json.loads((O/'results.json').read_text());source=json.loads((D/'development-assets.json').read_text());assert sha(O/'protocol.json')==data['protocol_sha256'] and sha(R/'research/r112_mask_hypotheses.py')==data['script_sha256'] and sha(D/'development-assets.json')==protocol['development_assets_sha256'] and sha('/tmp/mobile_sam.pt')==protocol['checkpoint_sha256'];assert [r['annotation_id'] for r in data['records']]==[r['annotation_id'] for r in source['records']] and all(r['split']=='development' for r in source['records']);indices={0,len(source['records'])-1};indices.add(next(i for i,r in enumerate(source['records']) if r['source_annotation_shape']=='Circle'));indices.add(next(i for i,r in enumerate(source['records']) if max(r['source_dimensions_px'])>512));replayed=0;maxq=0
for i,(row,orig) in enumerate(zip(data['records'],source['records'])):
 path=D/row['source_crop'];assert sha(path)==row['source_sha256']==orig['source_sha256'] and row['source_crop']==orig['source_crop'] and row['source_species']==orig['source_species'];im=np.asarray(Image.open(path).convert('L'));h,w=im.shape;assert row['source_dimensions_px']==[w,h];f=min(1.,512/max(w,h));iw,ih=max(1,round(w*f)),max(1,round(h*f));ox,oy=(512-iw)//2,(512-ih)//2;pts=points_for(orig);mpts=[[ox+x*iw/w,oy+y*ih/h] for x,y in pts];assert row['source_points_xy']==pts and row['inference_points_xy']==mpts and row['inference_input_size_px']==[iw,ih] and row['inference_padding_offset_xy']==[ox,oy];masks=[]
 for name in NAMES:
  v=row['masks'][name];maskp=O/v['file'];assert sha(maskp)==v['sha256'];m=np.asarray(Image.open(maskp).convert('L'))>0;assert m.shape==(h,w) and int(m.sum())==v['area_px'];masks.append(m)
 pairs=[]
 for a,b in ((0,1),(0,2),(1,2)):
  u=int((masks[a]|masks[b]).sum());pairs.append(int((masks[a]&masks[b]).sum())/u if u else 0.)
 coverage=int(masks[0].sum())/(w*h);expected='consistent-unverified' if min(pairs)>=.75 and .03<=coverage<=.75 else 'needs-inspection';assert row['pairwise_iou']==pairs and row['center_mask_crop_fraction']==coverage and row['triage']==expected
 if i in indices:
  resize=im if (iw,ih)==(w,h) else cv2.resize(im,(iw,ih),interpolation=cv2.INTER_AREA);can=np.full((512,512),int(np.median(im)),np.uint8);can[oy:oy+ih,ox:ox+iw]=resize;predictor=Predictor(overrides={'model':'/tmp/mobile_sam.pt','task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});predictor.set_image(cv2.cvtColor(can,cv2.COLOR_GRAY2BGR));p=predictor(points=[[[x,y]] for x,y in mpts],labels=[[1]]*3,verbose=False)[0]
  for k,(raw,score) in enumerate(zip(p.masks.data.cpu().numpy(),p.boxes.conf.cpu().numpy())):
   pred=cv2.resize(raw[oy:oy+ih,ox:ox+iw].astype('uint8'),(w,h),interpolation=cv2.INTER_NEAREST).astype(bool);assert np.array_equal(pred,masks[k]);maxq=max(maxq,abs(float(score)-row['masks'][NAMES[k]]['quality_model_score_not_accuracy']));replayed+=1
print(json.dumps({'development_sources':len(source['records']),'mask_hypotheses':len(source['records'])*3,'selected_cases_replayed':len(indices),'neural_queries_replayed':replayed,'maximum_score_difference':maxq,'checks':'Source and mask hashes, development-only selection, prompt coordinates, IoUs, triage and sampled full neural inference; no mask identity, taxonomy, independence or biological accuracy checked.'},indent=2))
