"""Freeze structurally usable public IDs before fetching their image pixels."""
import concurrent.futures,hashlib,json,sys
from pathlib import Path
import numpy as np
from PIL import Image
import r46_audit_boxes as boxes,r46_fetch_cases as source
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r64';TMP=Path('/tmp/diatom-r64-public');sys.path.insert(0,str(ROOT/'diatom_pilot'))
from mask_component_guard import candidates_from_binary
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 sel=json.loads((OUT/'selection.json').read_text());inv=ROOT/'results/r46/inventory.json'
 if sha(inv)!=sel['inventory_sha256']:raise ValueError('Inventory changed')
 for f,h in sel['excluded_selection_hashes'].items():
  if sha(ROOT/f)!=h:raise ValueError('Prior selection changed')
 sizes={r['name']:r['bytes'] for r in json.loads(inv.read_text())['files']};TMP.mkdir(exist_ok=True)
 def meta(ident):
  info=boxes.fetch(ident);data=source.get('annotations/'+ident+'.png',sizes['annotations/'+ident+'.png']);path=TMP/(ident+'-mask.png');path.write_bytes(data);rgb=np.asarray(Image.open(path).convert('RGB'));binary=((rgb==0).all(axis=2)|(rgb==255).all(axis=2));result=candidates_from_binary((rgb!=0).any(axis=2),[x['box'] for x in info['objects']],minimum_area=20,containment=.98) if binary.all() and info['objects'] else {'status':'ambiguous','reason':'nonbinary_or_no_boxes','instances':[]};return {'id':ident,'xml_sha256':info['xml_sha256'],'mask_sha256':sha(path),'result':result}
 audit=OUT/'mask-audit.json';usable=OUT/'usable-selection.json'
 if usable.exists():rows=json.loads(audit.read_text())['records'];chosen=json.loads(usable.read_text())['sources']
 else:
  with concurrent.futures.ThreadPoolExecutor(max_workers=3) as ex:
   rows=[]
   for r in ex.map(meta,sel['candidate_ids']):rows.append(r);print(f"{len(rows)}/24 annotation audit",flush=True)
  audit.write_text(json.dumps({'selection_sha256':sha(OUT/'selection.json'),'records':rows},indent=2)+'\n');chosen=[r for r in rows if r['result']['status']=='structural_match'][:6]
  if len(chosen)<6:raise ValueError('Insufficient structurally usable sources; audit retained')
  usable.write_text(json.dumps({'format':'r64-usable-v1','selection_sha256':sha(OUT/'selection.json'),'mask_audit_sha256':sha(audit),'sources':chosen,'warning':'Structural correspondence is not expert ground truth; different IDs do not guarantee biological independence.'},indent=2)+'\n');print('Frozen six IDs before image retrieval.',flush=True)
 def fetch(r):
  ident=r['id'];path=TMP/(ident+'-image.png');data=source.get('images/'+ident+'.png',sizes['images/'+ident+'.png']);path.write_bytes(data);return {'id':ident,'sha256':sha(path),'bytes':len(data)}
 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as ex:
  images=[]
  for r in ex.map(fetch,chosen):images.append(r);print(f'{len(images)}/6 images fetched',flush=True)
 (OUT/'download.json').write_text(json.dumps({'usable_selection_sha256':sha(usable),'images':images},indent=2)+'\n')
if __name__=='__main__':main()
