"""Rebuild source mappings, candidate metrics and sample inference for gate audit."""
import ctypes,hashlib,json,math,os,signal,xml.etree.ElementTree as ET
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];A=R/'results/r112/design/native-assets';O=R/'results/r112/design/mask-gate-audit';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());assets=json.loads((A/'manifest.json').read_text())['assets'];assert sha(A/'manifest.json')==protocol['assets_sha256'] and sha('/tmp/mobile_sam.pt')==protocol['checkpoint_sha256'] and sha(O/'protocol.json')==data['protocol_sha256'] and sha(R/'research/r112_mask_gate_audit.py')==data['script_sha256'] and [r['asset'] for r in data['records']]==[a['id'] for a in assets];replay={'asset-000','asset-002','asset-011','asset-053'};replayed=0;maxq=0
for row,asset in zip(data['records'],assets):
 s=asset['source'];ip=R/s['image_path'];assert sha(ip)==s['image_sha256'];img=np.asarray(Image.open(ip).convert('L'));H,W=img.shape;x0,y0,x1,y1=asset['source_crop_xyxy'];refpath=A/asset['source_support_mask'];assert sha(refpath)==asset['source_support_mask_sha256'];ref=np.asarray(Image.open(refpath).convert('L'))>0
 if 'xml_path' in s:
  xp=R/s['xml_path'];assert sha(xp)==s['xml_sha256'];obj=ET.parse(xp).getroot().findall('./objects/object')[s['box_index']];box=[int(obj.findtext('./bbox/'+k)) for k in ('xmin','ymin','xmax','ymax')];assert row['family']=='gunduz_box_component_proxy'
 else:box=[x0,y0,x1,y1];assert row['family']=='khanom_polygon'
 assert row['box_xyxy']==box;bx0,by0,bx1,by1=box;dx=max(16,math.ceil((bx1-bx0)*.25));dy=max(16,math.ceil((by1-by0)*.25));rx0,ry0=max(0,bx0-dx),max(0,by0-dy);rx1,ry1=min(W,bx1+dx),min(H,by1+dy);assert row['roi_xyxy']==[rx0,ry0,rx1,ry1];crop=img[ry0:ry1,rx0:rx1];h,w=crop.shape;ground=np.zeros((H,W),bool);ground[y0:y1,x0:x1]=ref;target=ground[ry0:ry1,rx0:rx1];assert sha(O/row['source_image'])==row['source_image_sha256'] and np.array_equal(crop,np.asarray(Image.open(O/row['source_image']).convert('L')));assert sha(O/row['reference'])==row['reference_sha256'] and np.array_equal(target,np.asarray(Image.open(O/row['reference']).convert('L'))>0);pts=points_for({'source_annotation_shape':'Rectangle','source_annotation_points_global':[bx0,by0,bx1,by0,bx1,by1,bx0,by1],'source_annotation_bbox_global':[rx0,ry0,rx1,ry1],'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;mpts=[[ox+x*iw/w,oy+y*ih/h] for x,y in pts];assert pts==row['points_xy'] and mpts==row['inference_points_xy'];masks=[]
 for name in NAMES:
  rec=row['masks'][name];mp=O/rec['file'];assert sha(mp)==rec['sha256'];m=np.asarray(Image.open(mp).convert('L'))>0;assert m.shape==(h,w);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.)
 union=int((masks[0]|target).sum());iou=int((masks[0]&target).sum())/union if union 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_reference_iou']==iou and row['center_mask_crop_fraction']==coverage and row['triage']==expected
 if row['asset'] in replay:
  resize=crop if (iw,ih)==(w,h) else cv2.resize(crop,(iw,ih),interpolation=cv2.INTER_AREA);can=np.full((512,512),int(np.median(crop)),np.uint8);can[oy:oy+ih,ox:ox+iw]=resize;p=Predictor(overrides={'model':'/tmp/mobile_sam.pt','task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.});p.set_image(cv2.cvtColor(can,cv2.COLOR_GRAY2BGR));result=p(points=[[[x,y]] for x,y in mpts],labels=[[1]]*3,verbose=False)[0]
  for k,(m,q) in enumerate(zip(result.masks.data.cpu().numpy(),result.boxes.conf.cpu().numpy())):
   pred=cv2.resize(m[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(q)-row['masks'][NAMES[k]]['quality']));replayed+=1
print(json.dumps({'cases':len(assets),'replayed_cases':len(replay),'neural_queries_replayed':replayed,'max_quality_difference':maxq,'scope':'Source hashes, reference geometry, source-provided or oracle box, prompts, triage, saved masks and four inference batches. Shared prompt helper; does not establish biological ground truth or sample independence.'},indent=2))
