"""Compare same-model source masks with previously used published polygons."""
import collections,ctypes,json,os,signal,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics.models.sam import Predictor
from r112_new_taxa_masks import points_for
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r112/source-mask-polygon-proxy';D=R/'datasets/r84-khanom';H=R/'results/r84';W=Path('/tmp/mobile_sam.pt')
def iou(a,b):
 u=int((a|b).sum());return float((a&b).sum()/u) if u else 0.
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);p=json.loads((O/'protocol.json').read_text());assert not (O/'results.json').exists() and sha(W)==p['weight_sha256']
 for f,h in p['inputs_sha256'].items():assert sha(R/f)==h,f
 selection=json.loads((H/'selection.json').read_text())['records'];files=json.loads((H/'image-manifest.json').read_text())['files'];assert len(selection)==len(files)==16;model=Predictor(overrides={'model':str(W),'task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'conf':0.});records=[];start=time.monotonic();(O/'images').mkdir(exist_ok=True)
 for idx,(ref,file) in enumerate(zip(selection,files)):
  assert sha(R/file['path'])==file['sha256'] and sha(D/ref['coco_file'])==ref['coco_sha256'];source=np.asarray(Image.open(R/file['path']).convert('L'));height,width=source.shape;assert [width,height]==[ref['width'],ref['height']];coco=json.loads((D/ref['coco_file']).read_text());annotations=[x for x in coco['annotations'] if x['image_id']==ref['image_id']];assert len(annotations)==ref['reference_count']
  for a in annotations:
   assert a['iscrowd']==0 and len(a['segmentation'])==1;points=np.asarray(a['segmentation'][0],dtype=np.float64).reshape(-1,2);bx,by,bw,bh=map(float,a['bbox']);margin=.15*max(bw,bh);x0=max(0,int(np.floor(bx-margin)));y0=max(0,int(np.floor(by-margin)));x1=min(width,int(np.ceil(bx+bw+margin)));y1=min(height,int(np.ceil(by+bh+margin)));im=source[y0:y1,x0:x1];h,w=im.shape;refmask=np.zeros((h,w),np.uint8);cv2.fillPoly(refmask,[np.rint(points-[x0,y0]).astype(np.int32)],1);refmask=refmask.astype(bool);assert refmask.any();pseudo={'source_annotation_points_global':points.tolist(),'source_annotation_bbox_global':[x0,y0,x1-1,y1-1],'source_dimensions_px':[w,h],'source_annotation_shape':'Polygon'};pts=points_for(pseudo);fac=min(1.,512/max(w,h));iw,ih=max(1,round(w*fac)),max(1,round(h*fac));img=im if (iw,ih)==(w,h) else cv2.resize(im,(iw,ih),interpolation=cv2.INTER_AREA);ox,oy=(512-iw)//2,(512-ih)//2;canvas=np.full((512,512),int(np.median(im)),np.uint8);canvas[oy:oy+ih,ox:ox+iw]=img;model_pts=[[ox+x*iw/w,oy+y*ih/h] for x,y in pts];model.set_image(cv2.cvtColor(canvas,cv2.COLOR_GRAY2BGR));out=model(points=[[[x,y]] for x,y in model_pts],labels=[[1]]*3,verbose=False)[0];assert out.masks is not None and len(out.masks.data)==3;arr=[];filesout={};case=f"f{idx:02d}-a{a['id']}"
   for name,raw,score in zip(('center','minus','plus'),out.masks.data.cpu().numpy(),out.boxes.conf.cpu().numpy()):
    part=raw[oy:oy+ih,ox:ox+iw].astype('uint8');mask=cv2.resize(part,(w,h),interpolation=cv2.INTER_NEAREST).astype(bool);arr.append(mask);path=O/'images'/f'{case}-{name}.png';Image.fromarray(mask.astype('uint8')*255).save(path);filesout[name]={'file':str(path.relative_to(O)),'sha256':sha(path),'area_px':int(mask.sum()),'model_quality_not_accuracy':float(score)}
   for name,x in [('crop',im),('reference',refmask.astype('uint8')*255)]:
    path=O/'images'/f'{case}-{name}.png';Image.fromarray(x).save(path);filesout[name]={'file':str(path.relative_to(O)),'sha256':sha(path)}
   pairs=[iou(arr[a0],arr[b0]) for a0,b0 in ((0,1),(0,2),(1,2))];coverage=float(arr[0].mean());status='consistent-unverified' if min(pairs)>=.75 and .03<=coverage<=.75 else 'needs-inspection';records.append({'id':case,'field_index':idx,'source_filename':ref['filename'],'source_folder':ref['species_from_folder'],'source_image_path':file['path'],'source_image_sha256':file['sha256'],'source_coco':ref['coco_file'],'source_coco_sha256':ref['coco_sha256'],'source_image_id':ref['image_id'],'annotation_id':a['id'],'crop_bounds_xyxy_exclusive':[x0,y0,x1,y1],'source_points_xy':pts,'model_points_xy':model_pts,'point_in_reference':[bool(refmask[min(h-1,max(0,round(y))),min(w-1,max(0,round(x)))]) for x,y in pts],'inference_input_size_px':[iw,ih],'inference_padding_offset_xy':[ox,oy],'proposal_pairwise_iou':pairs,'center_crop_fraction':coverage,'triage':status,'reference_iou':{k:iou(mask,refmask) for k,mask in zip(('center','minus','plus'),arr)},'images':filesout})
  print('fields',idx+1,'/',len(selection),'cases',len(records),'seconds',round(time.monotonic()-start,1),flush=True)
 assert len(records)==29;counts={}
 for group in ('consistent-unverified','needs-inspection'):
  sub=[x for x in records if x['triage']==group];counts[group]={'cases':len(sub),'center_iou_ge_0_5':sum(x['reference_iou']['center']>=.5 for x in sub),'center_iou_ge_0_75':sum(x['reference_iou']['center']>=.75 for x in sub),'all_points_inside_polygon':sum(all(x['point_in_reference']) for x in sub)}
 result={'format':p['format'],'protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'counts':counts,'records':records,'limitations':p['limitations']};(O/'results.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(counts,indent=2),flush=True)
if __name__=='__main__':main()
