"""Retrieve selected mask metadata, freeze structural cases, then fetch 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/r56';TMP=Path('/tmp/diatom-r56-public');sys.path.insert(0,str(ROOT/'diatom_pilot'))
from mask_component_guard import candidates_from_binary
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 selection=OUT/'candidate-selection.json';s=json.loads(selection.read_text());inv=ROOT/'results/r46/inventory.json'
 if sha(inv)!=s['inventory_sha256']:raise ValueError('Inventory changed')
 for file,h in s['excluded_selection_hashes'].items():
  if sha(ROOT/file)!=h:raise ValueError('Exclusion changed')
 sizes={r['name']:r['bytes'] for r in json.loads(inv.read_text())['files']};TMP.mkdir(parents=True,exist_ok=True)
 if (OUT/'usable-selection.json').exists():raise FileExistsError('Preserve prior selection')
 def get_meta(ident):
  info=boxes.fetch(ident);name='annotations/'+ident+'.png';data=source.get(name,sizes[name]);maskpath=TMP/(ident+'-mask.png');maskpath.write_bytes(data);rgb=np.asarray(Image.open(maskpath).convert('RGB'));binary=((rgb==0).all(axis=2)|(rgb==255).all(axis=2));res=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(maskpath),'result':res}
 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as ex:
  rows=[]
  for i,r in enumerate(ex.map(get_meta,s['ids']),1):rows.append(r);print(f'{i}/20 annotations audited',flush=True)
 (OUT/'mask-audit.json').write_text(json.dumps({'selection_sha256':sha(selection),'records':rows},indent=2)+'\n');usable=[r for r in rows if r['result']['status']=='structural_match'][:12]
 if len(usable)<12:raise ValueError('Fewer than 12 structurally valid cases; audit saved')
 dest=OUT/'usable-selection.json';dest.write_text(json.dumps({'format':'r56-usable-selection-v1','candidate_sha256':sha(selection),'mask_audit_sha256':sha(OUT/'mask-audit.json'),'sources':usable,'warning':'Selected after annotation audit but before image retrieval; structural mask correspondence is not expert ground truth or evidence of independent biological samples.'},indent=2)+'\n');print('Frozen twelve usable IDs before image retrieval.',flush=True)
 def get_image(r):
  ident=r['id'];name='images/'+ident+'.png';data=source.get(name,sizes[name]);path=TMP/(ident+'-image.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 i,r in enumerate(ex.map(get_image,usable),1):images.append(r);print(f'{i}/12 source images verified',flush=True)
 (OUT/'download.json').write_text(json.dumps({'selection_sha256':sha(dest),'images':images},indent=2)+'\n');print('Source retrieval complete.',flush=True)
if __name__=='__main__':main()
