"""Compare fixed three-prompt mask triage to prior source regions."""
import ctypes,hashlib,json,math,os,signal,time,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()
def main():
 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);proto=json.loads((O/'protocol.json').read_text());assert sha(A/'manifest.json')==proto['assets_sha256'] and sha('/tmp/mobile_sam.pt')==proto['checkpoint_sha256'] and sha(R/'results/r112/species-depth/mask-hypotheses/protocol.json')==proto['triage_protocol_sha256'];assets=json.loads((A/'manifest.json').read_text())['assets'];assert len(assets)==58;rows=[];start=time.monotonic()
 for i,asset in enumerate(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'];ref=np.asarray(Image.open(A/asset['source_support_mask']).convert('L'))>0;assert sha(A/asset['source_support_mask'])==asset['source_support_mask_sha256'] and ref.shape==(y1-y0,x1-x0)
  if 'xml_path' in s:
   xp=R/s['xml_path'];assert sha(xp)==s['xml_sha256'];objs=ET.parse(xp).getroot().findall('./objects/object');obj=objs[s['box_index']];box=[int(obj.findtext('./bbox/'+k)) for k in ('xmin','ymin','xmax','ymax')];family='gunduz_box_component_proxy';prompt_origin='source XML box'
  else:
   box=[x0,y0,x1,y1];family='khanom_polygon';prompt_origin='reference mask bounding box; oracle'
  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);crop=img[ry0:ry1,rx0:rx1];h,w=crop.shape;ref_full=np.zeros((H,W),bool);ref_full[y0:y1,x0:x1]=ref;ref_roi=ref_full[ry0:ry1,rx0:rx1];assert ref_roi.any();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));small=crop if (iw,ih)==(w,h) else cv2.resize(crop,(iw,ih),interpolation=cv2.INTER_AREA);ox,oy=(512-iw)//2,(512-ih)//2;can=np.full((512,512),int(np.median(crop)),np.uint8);can[oy:oy+ih,ox:ox+iw]=small;points=[[ox+x*iw/w,oy+y*ih/h] for x,y in pts];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));pred=p(points=[[[x,y]] for x,y in points],labels=[[1]]*3,verbose=False)[0];assert len(pred.masks.data)==3;masks=[];files={};ident=asset['id'];origpath=O/f'{ident}-source.png';refpath=O/f'{ident}-reference.png';Image.fromarray(crop).save(origpath);Image.fromarray(ref_roi.astype('uint8')*255).save(refpath)
  for name,raw,quality in zip(NAMES,pred.masks.data.cpu().numpy(),pred.boxes.conf.cpu().numpy()):
   m=cv2.resize(raw[oy:oy+ih,ox:ox+iw].astype('uint8'),(w,h),interpolation=cv2.INTER_NEAREST).astype(bool);masks.append(m);fn=O/f'{ident}-{name}.png';Image.fromarray(m.astype('uint8')*255).save(fn);files[name]={'file':fn.name,'sha256':sha(fn),'quality':float(quality)}
  pairs=[]
  for a,b in ((0,1),(0,2),(1,2)):
   union=int((masks[a]|masks[b]).sum());pairs.append(int((masks[a]&masks[b]).sum())/union if union else 0.)
  center=masks[0];union=int((center|ref_roi).sum());iou=int((center&ref_roi).sum())/union if union else 0.;fraction=int(center.sum())/(w*h);triage='consistent-unverified' if min(pairs)>=.75 and .03<=fraction<=.75 else 'needs-inspection';rows.append({'asset':ident,'family':family,'prompt_origin':prompt_origin,'source':s,'roi_xyxy':[rx0,ry0,rx1,ry1],'box_xyxy':box,'source_image':origpath.name,'source_image_sha256':sha(origpath),'reference':refpath.name,'reference_sha256':sha(refpath),'roi_size':[w,h],'points_xy':pts,'inference_size':[iw,ih],'inference_padding_offset':[ox,oy],'inference_points_xy':points,'masks':files,'pairwise_iou':pairs,'center_mask_crop_fraction':fraction,'triage':triage,'center_reference_iou':iou});(O/'partial.json').write_text(json.dumps({'records':rows},indent=2)+'\n')
  if (i+1)%10==0:print(i+1,'/ 58',round(time.monotonic()-start,1),'seconds',flush=True)
 (O/'results.json').write_text(json.dumps({'format':'r112-mask-gate-audit-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':rows,'warning':'Previously seen, non-independent reference proxies; Khanom prompts use oracle reference-derived boxes; no biological ground truth or real overlap validation.'},indent=2)+'\n');print('completed',len(rows),flush=True)
if __name__=='__main__':main()
