"""Fetch source image pixels for preselected R48 structural cases."""
import concurrent.futures,hashlib,json
from pathlib import Path
import r46_fetch_cases as source
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r48';SRC=ROOT/'results/r46';TEMP=Path('/tmp/diatom-r47-public/images')
def sha(x):return hashlib.sha256(x).hexdigest()
def main():
 dest=OUT/'image-download.json'
 if dest.exists():raise FileExistsError('Image report exists')
 raw=(OUT/'selection.json').read_bytes();p=json.loads((OUT/'protocol.json').read_text())
 if sha(raw)!=p['selection_sha256']:raise ValueError('Selection changed')
 rows=json.loads(raw)['selection'];sizes={x['name']:x['bytes'] for x in json.loads((SRC/'inventory.json').read_text())['files']};TEMP.mkdir(parents=True,exist_ok=True)
 def one(row):
  ident=row['id'];name='images/'+ident+'.png';path=TEMP/(ident+'.png');data=source.get(name,sizes[name])
  if path.exists() and path.read_bytes()!=data:raise ValueError('Existing file differs')
  if not path.exists():path.write_bytes(data)
  return {'id':ident,'sha256':sha(data),'bytes':len(data)}
 out=[]
 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
  futures=[pool.submit(one,r) for r in rows]
  for i,f in enumerate(concurrent.futures.as_completed(futures),1):
   out.append(f.result())
   if i%4==0:print(f'{i}/{len(rows)} selected source images verified',flush=True)
 hashes=[x['sha256'] for x in out]
 if len(set(hashes))!=len(hashes):raise ValueError('Duplicate source images require audit')
 dest.write_text(json.dumps({'format':'r48-image-download-v1','selection_sha256':sha(raw),'images':out},indent=2)+'\n');print('Source image retrieval complete.',flush=True)
if __name__=='__main__':main()
