"""Recompute crop/reference/proposal geometry and reported agreement statistics."""
import json
from pathlib import Path
import cv2,numpy as np
from PIL import Image
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';p=json.loads((O/'protocol.json').read_text());r=json.loads((O/'results.json').read_text());assert r['protocol_sha256']==sha(O/'protocol.json') and r['script_sha256']==sha(R/'research/r112_polygon_proxy_compare.py')
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h,f
def iou(a,b):
 u=int((a|b).sum());return float((a&b).sum()/u) if u else 0.
seen=set()
for x in r['records']:
 k=(x['field_index'],x['annotation_id']);assert k not in seen;seen.add(k);im=np.asarray(Image.open(R/x['source_image_path']).convert('L'));coco=json.loads((D/x['source_coco']).read_text());matches=[a for a in coco['annotations'] if a['id']==x['annotation_id'] and a['image_id']==x['source_image_id']];assert len(matches)==1;a=matches[0];pts=np.asarray(a['segmentation'][0],dtype=np.float64).reshape(-1,2);bx,by,bw,bh=map(float,a['bbox']);m=.15*max(bw,bh);x0=max(0,int(np.floor(bx-m)));y0=max(0,int(np.floor(by-m)));x1=min(im.shape[1],int(np.ceil(bx+bw+m)));y1=min(im.shape[0],int(np.ceil(by+bh+m)));assert [x0,y0,x1,y1]==x['crop_bounds_xyxy_exclusive'];crop=im[y0:y1,x0:x1];h,w=crop.shape;ref=np.zeros((h,w),np.uint8);cv2.fillPoly(ref,[np.rint(pts-[x0,y0]).astype(np.int32)],1);ref=ref.astype(bool);paths={k:O/v['file'] for k,v in x['images'].items()}
 for k,path in paths.items():assert sha(path)==x['images'][k]['sha256']
 assert np.array_equal(np.asarray(Image.open(paths['crop'])),crop) and np.array_equal(np.asarray(Image.open(paths['reference']))>0,ref);pred=[]
 for name in ('center','minus','plus'):
  raw=np.asarray(Image.open(paths[name]));assert raw.shape==ref.shape and set(np.unique(raw)).issubset({0,255});mask=raw>0;assert int(mask.sum())==x['images'][name]['area_px'] and abs(iou(mask,ref)-x['reference_iou'][name])<1e-12;pred.append(mask)
 pairs=[iou(pred[a0],pred[b0]) for a0,b0 in ((0,1),(0,2),(1,2))];cover=float(pred[0].mean());assert np.allclose(pairs,x['proposal_pairwise_iou']) and abs(cover-x['center_crop_fraction'])<1e-12;assert x['triage']==('consistent-unverified' if min(pairs)>=.75 and .03<=cover<=.75 else 'needs-inspection');pseudo={'source_annotation_points_global':pts.tolist(),'source_annotation_bbox_global':[x0,y0,x1-1,y1-1],'source_dimensions_px':[w,h],'source_annotation_shape':'Polygon'};q=points_for(pseudo);assert np.allclose(q,x['source_points_xy']);assert [bool(ref[min(h-1,max(0,round(y))),min(w-1,max(0,round(xx)))]) for xx,y in q]==x['point_in_reference'];factor=min(1.,512/max(w,h));iw,ih=max(1,round(w*factor)),max(1,round(h*factor));ox,oy=(512-iw)//2,(512-ih)//2;assert x['inference_input_size_px']==[iw,ih] and x['inference_padding_offset_xy']==[ox,oy] and np.allclose(x['model_points_xy'],[[ox+xx*iw/w,oy+y*ih/h] for xx,y in q])
assert len(seen)==29
for group in ('consistent-unverified','needs-inspection'):
 xs=[x for x in r['records'] if x['triage']==group];assert r['counts'][group]=={'cases':len(xs),'center_iou_ge_0_5':sum(x['reference_iou']['center']>=.5 for x in xs),'center_iou_ge_0_75':sum(x['reference_iou']['center']>=.75 for x in xs),'all_points_inside_polygon':sum(all(x['point_in_reference']) for x in xs)}
report={'format':'r112-source-mask-polygon-proxy-verify-v1','results_sha256':sha(O/'results.json'),'cases':len(seen),'counts':r['counts'],'checks':'All input hashes, source-derived crops, polygon rasterization, saved mask hashes, prompt coordinates, per-case IoUs and summaries reconstructed. Model inference was not rerun. Published polygon quality, independence and biological correctness are not established.'};(O/'verify.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
