"""Fetch frozen public XML/binary masks, structurally audit before seeing images."""
import json,hashlib,concurrent.futures
from pathlib import Path
import 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
R=Path(__file__).resolve().parents[1];O=R/'results/r91';D=R/'datasets/r91-gunduz';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 p=json.loads((O/'protocol.json').read_text());assert sha(R/'results/r46/inventory.json')==p['inventory_sha256'];sizes={x['name']:x['bytes'] for x in json.loads((R/'results/r46/inventory.json').read_text())['files']};boxes.TEMP=D/'xml';
 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 e:out=list(e.map(fetch,p['preselection']))
 valid=[r for r in out if r['status']=='structural_match'][:12];assert len(valid)>=1;result={'format':'r91-metadata-audit-v1','protocol_sha256':sha(O/'protocol.json'),'records':out,'selected':[r['id'] for r in valid],'warning':'Structural matching only; boxes cannot establish real individual overlap, sample independence or exhaustive annotations. Images have not been fetched.'};(O/'metadata-audit.json').write_text(json.dumps(result,indent=2)+'\n');print('audited',len(out),'structural matches',sum(r['status']=='structural_match' for r in out),'selected',result['selected'],flush=True)
if __name__=='__main__':main()
