"""Fetch selected source metadata/masks, freeze usable IDs, 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/l42';TMP=Path('/tmp/diatom-l42-sources');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());sizes={x['name']:x['bytes'] for x in json.loads((ROOT/'results/r46/inventory.json').read_text())['files']};TMP.mkdir(parents=True,exist_ok=True)
 if (OUT/'usable-selection.json').exists():raise FileExistsError('Usable selection exists')
 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))
  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(maskpath),'result':result}
 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as ex:records=list(ex.map(get_meta,s['ids']))
 usable=[r for r in records if r['result']['status']=='structural_match'][:6]
 if len(usable)<6:raise ValueError('Not enough usable masks; preserve audit and extend selection with new declared rule')
 (OUT/'mask-audit.json').write_text(json.dumps({'selection_sha256':sha(selection),'records':records},indent=2)+'\n');dest=OUT/'usable-selection.json';dest.write_text(json.dumps({'format':'l42-usable-selection-v1','candidate_sha256':sha(selection),'mask_audit_sha256':sha(OUT/'mask-audit.json'),'sources':usable,'warning':'Selected after annotation inspection but before source image pixels. Binary component association is structural, not biological ground truth.'},indent=2)+'\n')
 print('Frozen six structurally usable IDs before reading image pixels.',flush=True)
 def get_image(row):
  ident=row['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=list(ex.map(get_image,usable))
 (OUT/'download.json').write_text(json.dumps({'selection_sha256':sha(dest),'images':images},indent=2)+'\n');print('Source image download complete.',flush=True)
if __name__=='__main__':main()
