"""Fetch frozen source annotations and select structurally mapped components."""
import concurrent.futures,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image
import r46_audit_boxes as boxes
import r46_fetch_cases as source
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'
def main():
 p=json.loads((O/'protocol.json').read_text());assert not (O/'annotation-audit.json').exists() and sha(R/'results/r46/inventory.json')==p['inventory_sha256'] and sha(O/'prior-id-screen.json')==p['id_screen_sha256'];sizes={x['name']:x['bytes'] for x in json.loads((R/'results/r46/inventory.json').read_text())['files']};boxes.TEMP=D/'xml';cv2.setNumThreads(2)
 def fetch(ident):
  info=boxes.fetch(ident);path=D/'masks'/f'{ident}.png';name=f'annotations/{ident}.png';data=source.get(name,sizes[name]);
  if path.exists() and path.read_bytes()!=data:raise ValueError('Existing mask differs')
  if not path.exists():path.write_bytes(data)
  rgb=np.asarray(Image.open(path).convert('RGB'));h,w=rgb.shape[:2];assert [w,h]==info['size'];binary=((rgb==0).all(axis=2)|(rgb==255).all(axis=2))
  if not binary.all():res={'status':'ambiguous','reason':'nonbinary','instances':[]}
  elif not info['objects']:res={'status':'ambiguous','reason':'no_boxes','instances':[]}
  else:res=candidates_from_binary((rgb!=0).any(axis=2),[x['box'] for x in info['objects']],minimum_area=20,containment=.98)
  return {'id':ident,'xml_sha256':info['xml_sha256'],'mask_sha256':sha(path),'size':info['size'],'objects':info['objects'],'overlapping_box_pairs':info['overlapping_box_pairs'],**res}
 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:rows=list(pool.map(fetch,p['preselection']))
 selected=[]
 for x in rows:
  if x['status']=='structural_match' and len(selected)<24:
   chosen=sorted(x['instances'],key=lambda k:(-k['area'],k['box_index']))[0];selected.append({'id':x['id'],'box_index':chosen['box_index'],'component_label':chosen['component_label'],'component_area':chosen['area']})
 assert len(selected)==24,('Only',len(selected),'structural matches');out={'format':'r115-gunduz-annotation-audit-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':rows,'selected':selected,'warning':'Metadata and binary-mask structural matching only; no source image pixels opened. Components and boxes are source annotations, not expert-confirmed individual masks. Sample and model independence unknown.'};(O/'annotation-audit.json').write_text(json.dumps(out,indent=2)+'\n');print('audited',len(rows),'structural matches',sum(x['status']=='structural_match' for x in rows),'selected',len(selected),flush=True)
if __name__=='__main__':main()
