"""Verify 61 cached-prefix source crops, physical transforms and sample mask replays."""
import csv,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
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/ude-prefix';D=R/'results/r14/prefix';META=Path('/tmp/ude-metadata.csv')
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 os.getppid()!=parent:raise RuntimeError('launcher exited')
torch.set_num_threads(2);cv2.setNumThreads(2);p=json.loads((O/'manifest.json').read_text());assert sha(R/'research/r112_ude_prefix.py')==p['script_sha256'] and sha(D/'reference-manifest.json')==p['selection_sha256'] and sha(META)==p['metadata_sha256'] and sha('/tmp/mobile_sam.pt')==p['model_sha256'];calpath=R/'results/r112/design/native-scenes/background-calibration.json';assert sha(calpath)==p['target_calibration_sha256'];bgs=json.loads(calpath.read_text())['scenes'][:8];selection=json.loads((D/'reference-manifest.json').read_text());expected=selection['rows'];assert [x['annotation_id'] for x in p['records']]==[x['annotation_id'] for x in expected];wanted={r['annotation_id'] for r in expected};meta={}
with META.open(newline='') as f:
 for row in csv.DictReader(f):
  if row['annotation_id'] in wanted:meta[row['annotation_id']]=row
assert len(meta)==len(expected)==61
maxq=0;sampled=0;reduced=0
for i,(r,origin) in enumerate(zip(p['records'],expected)):
 ident=r['annotation_id'];m=meta[ident];src=R/r['source_image'];assert sha(src)==r['source_sha256']==origin['sha256'] and r['source_image']==str((D/origin['local_file']).relative_to(R));im=np.asarray(Image.open(src).convert('L'));h,w=im.shape;assert [w,h]==r['source_crop_size_px'] and r['source_species']==m['species'] and r['source_genus']==m['genus'] and r['annotation_shape']==m['shape'] and r['annotation_points_global']==json.loads(m['points']);coords=[int(m['bbox_x0']),int(m['bbox_y0']),int(m['bbox_x1']),int(m['bbox_y1'])];assert coords==r['annotation_bbox_global'] and r['crop_vs_annotation_bbox_delta_px']==[w-(coords[2]-coords[0]+1),h-(coords[3]-coords[1]+1)]
 c=bgs[i%8];tx=c['background_um_per_pixel_x'];ty=c['background_um_per_pixel_y'];assert r['target_slide']==c['slide'] and r['source_um_per_pixel_xy']==[.09,.09] and r['target_um_per_pixel_xy']==[tx,ty];tw=max(1,round(w*.09/tx));th=max(1,round(h*.09/ty));assert r['target_crop_size_px']==[tw,th] and sha(O/r['scaled_image'])==r['scaled_sha256'] and np.array_equal(np.asarray(Image.open(O/r['scaled_image'])),cv2.resize(im,(tw,th),interpolation=cv2.INTER_AREA))
 for k,v in r['mask_proposals'].items():
  a=O/v['mask'];b=O/v['scaled_mask'];assert sha(a)==v['sha256'] and sha(b)==v['scaled_sha256'];ma=(np.asarray(Image.open(a).convert('L'))>0).astype('uint8');assert ma.shape==(h,w) and int(ma.sum())==v['area_pixels'] and np.array_equal((np.asarray(Image.open(b).convert('L'))>0).astype('uint8'),cv2.resize(ma,(tw,th),interpolation=cv2.INTER_NEAREST))
 factor=min(1.0,512/max(h,w));iw=max(1,round(w*factor));ih=max(1,round(h*factor));ox=(512-iw)//2;oy=(512-ih)//2;assert r['model_input_content_px']==[iw,ih] and r['model_input_offset_xy']==[ox,oy] and r['inference_downsample_ratio']==factor;reduced+=int(factor<1)
 if i in (0,15,30,45):
  in_img=im if (iw,ih)==(w,h) else cv2.resize(im,(iw,ih),interpolation=cv2.INTER_AREA);canvas=np.full((512,512),int(np.median(im)),np.uint8);canvas[oy:oy+ih,ox:ox+iw]=in_img;predict=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});predict.set_image(cv2.cvtColor(canvas,cv2.COLOR_GRAY2BGR));pt=[ox+iw//2,oy+ih//2];box=[ox,oy,ox+iw-1,oy+ih-1];assert r['model_prompt_point_xy']==pt and r['model_prompt_box_xyxy']==box
  for kind,result in [('point',predict(points=[[pt]],labels=[[1]],verbose=False)[0]),('box',predict(bboxes=[box],verbose=False)[0])]:
   raw=result.masks.data.cpu().numpy()[0,oy:oy+ih,ox:ox+iw].astype('uint8');predicted=cv2.resize(raw,(w,h),interpolation=cv2.INTER_NEAREST)>0;saved=np.asarray(Image.open(O/r['mask_proposals'][kind]['mask']).convert('L'))>0;assert np.array_equal(predicted,saved);maxq=max(maxq,abs(float(result.boxes.conf[0])-r['mask_proposals'][kind]['quality_model_score_not_accuracy']));sampled+=1
print(json.dumps({'assets':len(expected),'source_slide_groups':len({r['source_slide'] for r in expected}),'inference_downsampled':reduced,'replayed_model_queries':sampled,'sample_masks_identical':True,'max_quality_difference':maxq,'checks':'Hashes, metadata, target calibration, all resized images/masks and eight neural query replays; source labels and masks remain unverified; same-slide images are correlated.'},indent=2))
