"""Reconstruct all source component, proposal, triage and scoring calculations."""
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/r115';D=R/'datasets/r115-gunduz';p=json.loads((O/'protocol.json').read_text());r=json.loads((O/'results.json').read_text());a=json.loads((O/'annotation-audit.json').read_text());av=json.loads((O/'annotation-verify.json').read_text());manifest=json.loads((O/'image-manifest.json').read_text());s=json.loads((O/'leak-screen.json').read_text());sv=json.loads((O/'leak-screen-verify.json').read_text());assert r['protocol_sha256']==a['protocol_sha256']==manifest['protocol_sha256']==s['protocol_sha256']==sha(O/'protocol.json') and r['annotation_audit_sha256']==av['audit_sha256']==sha(O/'annotation-audit.json') and r['image_manifest_sha256']==sha(O/'image-manifest.json') and r['leak_screen_sha256']==sv['screen_sha256']==sha(O/'leak-screen.json') and r['script_sha256']==sha(R/'research/r115_evaluate.py')
for f,h in p['implementation_sha256'].items():assert sha(R/f)==h,f
sel={x['id']:x for x in a['selected']};meta={x['id']:x for x in a['records']};im={x['id']:x for x in manifest['records']};screen={x['id']:x for x in s['records']};assert [x['id'] for x in r['records']]==[x['id'] for x in manifest['records']] and len(r['records'])==24
names=['center','minus','plus']
def iou(a,b):
 u=int((a|b).sum());return float((a&b).sum()/u) if u else 0.
for row in r['records']:
 ident=row['id'];assert row['status']==('quarantined' if screen[ident]['quarantined'] else 'evaluated')
 if row['status']=='quarantined':assert row['minimum_crop_distance']==screen[ident]['minimum_crop_distance'];continue
 sourcepath=R/row['source_path'];assert sha(sourcepath)==row['source_sha256']==im[ident]['sha256'];maskpath=D/'masks'/f'{ident}.png';assert sha(maskpath)==meta[ident]['mask_sha256'];source=np.asarray(Image.open(sourcepath).convert('L'));binary=np.asarray(Image.open(maskpath).convert('L'))>0;_,labels=cv2.connectedComponents(binary.astype('uint8'),connectivity=8);chosen=sel[ident];assert (row['component_label'],row['component_area_full'],row['box_index'])==(chosen['component_label'],chosen['component_area'],chosen['box_index']);ref=labels==chosen['component_label'];assert int(ref.sum())==chosen['component_area'];contours,_=cv2.findContours(ref.astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);contour=max(contours,key=cv2.contourArea).reshape(-1,2);box=meta[ident]['objects'][chosen['box_index']]['box'];assert box==row['source_box'];bx,by,bxx,byy=box;margin=.15*max(bxx-bx,byy-by);x0=max(0,int(np.floor(bx-margin)));y0=max(0,int(np.floor(by-margin)));x1=min(source.shape[1],int(np.ceil(bxx+margin)));y1=min(source.shape[0],int(np.ceil(byy+margin)));assert [x0,y0,x1,y1]==row['crop_bounds_xyxy_exclusive'];crop=source[y0:y1,x0:x1];target=ref[y0:y1,x0:x1];h,w=crop.shape;paths={k:O/v['file'] for k,v in row['images'].items()}
 for k,path in paths.items():assert sha(path)==row['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,target);q=points_for({'source_annotation_points_global':contour.tolist(),'source_annotation_bbox_global':[x0,y0,x1-1,y1-1],'source_dimensions_px':[w,h],'source_annotation_shape':'Polygon'});assert np.allclose(q,row['points_xy']) and [bool(target[min(h-1,max(0,round(y))),min(w-1,max(0,round(x)))]) for x,y in q]==row['points_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 row['inference_input_size_px']==[iw,ih] and row['inference_padding_offset_xy']==[ox,oy] and np.allclose(row['model_points_xy'],[[ox+x*iw/w,oy+y*ih/h] for x,y in q]);masks=[]
 for k in names:
  img=np.asarray(Image.open(paths[k]));assert img.shape==target.shape and set(np.unique(img)).issubset({0,255});m=img>0;assert int(m.sum())==row['images'][k]['area_px'] and abs(iou(m,target)-row['proposal_reference_iou'][k])<1e-12;masks.append(m)
 a0,b,c=[iou(masks[i],masks[j]) for i,j in ((0,1),(0,2),(1,2))];assert np.allclose([a0,b,c],row['pairwise_iou']);coverage=float(masks[0].mean());assert abs(coverage-row['center_crop_fraction'])<1e-12;triage='consistent-unverified' if min(a0,b,c)>=.75 and .03<=coverage<=.75 else 'needs-inspection';assert row['triage']==triage;scores=[a0+b,a0+c,b+c];md=max(range(3),key=lambda i:(scores[i],-i));gd=md if triage=='needs-inspection' else 0;assert row['medoid_choice']==names[md] and row['gated_choice']==names[gd] and row['scores']=={'center':iou(masks[0],target),'medoid':iou(masks[md],target),'gated':iou(masks[gd],target)}
evals=[x for x in r['records'] if x['status']=='evaluated'];assert r['quarantined_count']==sum(x['status']=='quarantined' for x in r['records'])
for group in ('all','consistent-unverified','needs-inspection'):
 xs=[x for x in evals if group=='all' or x['triage']==group];summary={'cases':len(xs),'methods':{k:{'iou_ge_0_5':sum(x['scores'][k]>=.5 for x in xs),'iou_ge_0_75':sum(x['scores'][k]>=.75 for x in xs),'mean_iou':float(np.mean([x['scores'][k] for x in xs])) if xs else None,'median_iou':float(np.median([x['scores'][k] for x in xs])) if xs else None} for k in ('center','medoid','gated')},'medoid_better':sum(x['scores']['medoid']>x['scores']['center']+1e-9 for x in xs),'medoid_worse':sum(x['scores']['medoid']<x['scores']['center']-1e-9 for x in xs),'gated_better':sum(x['scores']['gated']>x['scores']['center']+1e-9 for x in xs),'gated_worse':sum(x['scores']['gated']<x['scores']['center']-1e-9 for x in xs)};assert summary==r['summary'][group]
out={'format':'r115-gunduz-verify-v1','results_sha256':sha(O/'results.json'),'selected':len(r['records']),'quarantined':r['quarantined_count'],'evaluated':len(evals),'checks':'Selection and quarantines, all crop pixels, source component masks, source and prediction hashes, reference-derived prompts, per-case geometric decisions and aggregate scores reconstructed. Coarse leak screen independently replayed; neural inference not rerun. Proxy boundaries, absence of training leakage and biological independence not established.'};(O/'verify.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2))
