"""Fetch only predeclared metadata-selected public images; preserve hashes."""
import hashlib,json,concurrent.futures
from pathlib import Path
import r46_fetch_cases as source
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():
 audit=json.loads((O/'metadata-audit.json').read_text());p=json.loads((O/'protocol.json').read_text());assert audit['protocol_sha256']==sha(O/'protocol.json');sizes={v['name']:v['bytes'] for v in json.loads((R/'results/r46/inventory.json').read_text())['files']}
 def fetch(ident):
  name=f'images/{ident}.png';path=D/'images'/f'{ident}.png';data=source.get(name,sizes[name]);
  if path.exists() and path.read_bytes()!=data:raise ValueError('Existing image differs')
  if not path.exists():path.write_bytes(data)
  return {'id':ident,'path':str(path.relative_to(R)),'bytes':len(data),'sha256':sha(path)}
 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as e:records=list(e.map(fetch,audit['selected']))
 (O/'image-manifest.json').write_text(json.dumps({'format':'r91-image-manifest-v1','protocol_sha256':sha(O/'protocol.json'),'metadata_audit_sha256':sha(O/'metadata-audit.json'),'records':records},indent=2)+'\n');print('Downloaded',len(records),'source images',flush=True)
if __name__=='__main__':main()
