"""Fetch only the predeclared structurally eligible public source images."""
import concurrent.futures,json
from pathlib import Path
import r46_fetch_cases as source
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r115';D=R/'datasets/r115-gunduz'
def main():
 a=json.loads((O/'annotation-audit.json').read_text());assert a['protocol_sha256']==sha(O/'protocol.json') and not (O/'image-manifest.json').exists();sizes={x['name']:x['bytes'] for x in json.loads((R/'results/r46/inventory.json').read_text())['files']}
 def fetch(row):
  ident=row['id'];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 pool:rows=list(pool.map(fetch,a['selected']))
 result={'format':'r115-gunduz-image-manifest-v1','protocol_sha256':sha(O/'protocol.json'),'annotation_audit_sha256':sha(O/'annotation-audit.json'),'script_sha256':sha(__file__),'records':rows};(O/'image-manifest.json').write_text(json.dumps(result,indent=2)+'\n');print('downloaded',len(rows),'source images',flush=True)
if __name__=='__main__':main()
