"""Retrieve only frozen R43 targets; ZIP verifies member CRC."""
import hashlib,json,zipfile
from pathlib import Path
from r16_archive_inspect import Remote
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r43';DEST=Path('/tmp/diatom-r43-public');DEST.mkdir(exist_ok=True)
def sha(b):return hashlib.sha256(b).hexdigest()
def main():
 p=json.loads((OUT/'protocol.json').read_text());selection=(OUT/'selection.json').read_bytes()
 if sha(selection)!=p['selection_sha256']:raise ValueError('Selection changed')
 rows=json.loads(selection)['selection'];report=[]
 with zipfile.ZipFile(Remote()) as archive:
  for i,row in enumerate(rows,1):
   target=DEST/f'{i:02}.jpg';data=archive.read(row['zip_member'])
   if target.exists() and target.read_bytes()!=data:raise ValueError('Existing file differs from archive')
   if not target.exists():target.write_bytes(data)
   report.append({'index':i,'filename':row['image']['file_name'],'zip_member':row['zip_member'],'sha256':sha(data),'bytes':len(data)})
   print(f'{i}/{len(rows)} selected public images verified',flush=True)
 (OUT/'download-report.json').write_text(json.dumps({'selection_sha256':sha(selection),'images':report},indent=2)+'\n')
 print('Public polygon image retrieval complete.',flush=True)
if __name__=='__main__':main()
