"""Fetch preselected ZIP members with source length and CRC validation."""
import concurrent.futures,hashlib,json,zlib
from pathlib import Path
from r44_fetch_member import fetch
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l43';TEMP=Path('/tmp/diatom-l43-fields')
def sha(b):return hashlib.sha256(b).hexdigest()
def main():
 raw=(OUT/'selection.json').read_bytes();s=json.loads(raw);idx=ROOT/'results/r44/archive-index.json'
 if sha(idx.read_bytes())!=s['archive_index_sha256']:raise ValueError('Index changed')
 entries={e['name']:e for e in json.loads(idx.read_text())['entries']};TEMP.mkdir(exist_ok=True)
 if (OUT/'download.json').exists():raise FileExistsError('Preserve report')
 def one(r):
  e=entries[r['member']];p=TEMP/r['local_file']
  if e['crc32']!=r['archive_crc32'] or e['bytes']>1000000:raise ValueError('Unexpected entry')
  if p.exists():
   data=p.read_bytes()
   if len(data)!=e['bytes'] or f'{zlib.crc32(data)&0xffffffff:08x}'!=e['crc32']:raise ValueError('Existing file differs')
  else:
   data=fetch(e);p.write_bytes(data)
  return {'id':r['id'],'sha256':sha(data),'bytes':len(data)}
 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as ex:
  rows=[]
  futures=[ex.submit(one,r) for r in s['selection']]
  for i,f in enumerate(concurrent.futures.as_completed(futures),1):rows.append(f.result());print(f'{i}/12 fields verified',flush=True)
 (OUT/'download.json').write_text(json.dumps({'selection_sha256':sha(raw),'images':rows},indent=2)+'\n');print('Field download complete.',flush=True)
if __name__=='__main__':main()
