"""Post-hoc, reference-free medoid choice from an existing three-mask result."""
import json
from pathlib import Path
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r112/source-mask-polygon-proxy';source=json.loads((O/'results.json').read_text());names=['center','minus','plus'];rows=[]
for x in source['records']:
 a,b,c=x['proposal_pairwise_iou'];scores=[a+b,a+c,b+c];k=max(range(3),key=lambda i:(scores[i],-i));chosen=names[k];rows.append({'id':x['id'],'triage':x['triage'],'candidate_agreement_sums':scores,'chosen':chosen,'center_reference_iou':x['reference_iou']['center'],'chosen_reference_iou':x['reference_iou'][chosen],'gated_choice':chosen if x['triage']=='needs-inspection' else 'center','gated_reference_iou':x['reference_iou'][chosen if x['triage']=='needs-inspection' else 'center']})
counts={}
for group in ('all','consistent-unverified','needs-inspection'):
 sub=[x for x in rows if group=='all' or x['triage']==group];counts[group]={'cases':len(sub),'medoid_not_center':sum(x['chosen']!='center' for x in sub),'center_iou_ge_0_5':sum(x['center_reference_iou']>=.5 for x in sub),'medoid_iou_ge_0_5':sum(x['chosen_reference_iou']>=.5 for x in sub),'center_iou_ge_0_75':sum(x['center_reference_iou']>=.75 for x in sub),'medoid_iou_ge_0_75':sum(x['chosen_reference_iou']>=.75 for x in sub),'gated_iou_ge_0_5':sum(x['gated_reference_iou']>=.5 for x in sub),'gated_iou_ge_0_75':sum(x['gated_reference_iou']>=.75 for x in sub),'medoid_strictly_better':sum(x['chosen_reference_iou']>x['center_reference_iou']+1e-9 for x in sub),'medoid_strictly_worse':sum(x['chosen_reference_iou']<x['center_reference_iou']-1e-9 for x in sub)}
out={'format':'r112-polygon-proxy-medoid-v1','source_results_sha256':sha(O/'results.json'),'script_sha256':sha(__file__),'decision':'Choose the proposal with the largest sum of IoUs to the other two, with ties center, minus, plus. Choice uses only proposals, not the reference polygon. A second gated variant applies this choice only when existing triage flags the triad, otherwise keeping center. Both rules were tested after reviewing the 29 results and are exploratory, not a frozen independent test.','warning':'Agreement may consistently select the wrong structure. Author polygons have unknown expert status and boundary convention. Source fields were previously used; crops and prompts derive from reference polygons. No real-field, Academy, species, training data correctness or generalized performance claim.','counts':counts,'records':rows};(O/'medoid-exploration.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(counts,indent=2))
