"""Fetch and verify preselected public images and bounding-box labels."""
import concurrent.futures,hashlib,json,urllib.request
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r74';DEST=Path('/tmp/diatom-r74-public')
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 s=json.loads((OUT/'pair-selection.json').read_text());assert sha(OUT/'file-inventory.json')==s['file_inventory_sha256'];DEST.mkdir(exist_ok=True)
 if (OUT/'download.json').exists():raise FileExistsError('Preserve existing download')
 items=[(i,kind,row[kind]) for i,row in enumerate(s['pairs'],1) for kind in ('image','label')]
 def get(item):
  i,kind,entry=item;size=int(entry['bytes']);req=urllib.request.Request(entry['url'],headers={'User-Agent':'diatom-public-research/1.0'})
  with urllib.request.urlopen(req,timeout=60) as response:data=response.read(size+1)
  if len(data)!=size or hashlib.sha256(data).hexdigest()!=entry['sha256']:raise ValueError('Published file size/hash mismatch')
  path=DEST/(f'{i:02d}-{kind}'+Path(entry['name']).suffix.lower());path.write_bytes(data);return {'index':i,'kind':kind,'file':str(path),'bytes':size,'sha256':entry['sha256']}
 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as ex:rows=list(ex.map(get,items))
 (OUT/'download.json').write_text(json.dumps({'format':'r74-download-v1','selection_sha256':sha(OUT/'pair-selection.json'),'files':rows},indent=2)+'\n');print('Downloaded and verified',len(rows),'public files',flush=True)
if __name__=='__main__':main()
