"""Recompute every structural mapping and the fixed metadata selection."""
import json
from pathlib import Path
import cv2,numpy as np
from PIL import Image
import r46_audit_boxes as boxes
from diatom_pilot.mask_component_guard import candidates_from_binary
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());a=json.loads((O/'annotation-audit.json').read_text());assert a['protocol_sha256']==sha(O/'protocol.json') and a['script_sha256']==sha(R/'research/r115_annotation_audit.py') and len(a['records'])==48 and [x['id'] for x in a['records']]==p['preselection'];boxes.TEMP=D/'xml';selected=[]
for row in a['records']:
 ident=row['id'];x=boxes.fetch(ident);assert x['xml_sha256']==row['xml_sha256'] and x['size']==row['size'] and x['objects']==row['objects'] and x['overlapping_box_pairs']==row['overlapping_box_pairs'];mask=D/'masks'/f'{ident}.png';assert sha(mask)==row['mask_sha256'];rgb=np.asarray(Image.open(mask).convert('RGB'));assert [rgb.shape[1],rgb.shape[0]]==row['size'];binary=((rgb==0).all(2)|(rgb==255).all(2))
 if not binary.all():res={'status':'ambiguous','reason':'nonbinary','instances':[]}
 elif not x['objects']:res={'status':'ambiguous','reason':'no_boxes','instances':[]}
 else:res=candidates_from_binary((rgb!=0).any(2),[z['box'] for z in x['objects']],minimum_area=20,containment=.98)
 assert all(row[k]==v for k,v in res.items())
 if row['status']=='structural_match' and len(selected)<24:
  chosen=sorted(row['instances'],key=lambda z:(-z['area'],z['box_index']))[0];selected.append({'id':ident,'box_index':chosen['box_index'],'component_label':chosen['component_label'],'component_area':chosen['area']})
assert selected==a['selected'] and len(selected)==24;out={'format':'r115-gunduz-annotation-verify-v1','audit_sha256':sha(O/'annotation-audit.json'),'source_files':len(a['records']),'structural_matches':sum(x['status']=='structural_match' for x in a['records']),'selected':len(selected),'checks':'All 48 XML and foreground-mask file hashes, boxes, components and fixed-order selection recomputed before use. This validates structural mapping only, not biological instances, source quality or sample independence.'};(O/'annotation-verify.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2))
