"""Fetch the frozen selection of small River Menne 512-pixel tiles."""
import hashlib,json
from pathlib import Path
from r44_fetch_member import fetch
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r44';DEST=Path('/tmp/diatom-r44-menne/images')
def sha(b):return hashlib.sha256(b).hexdigest()
def main():
 protocol=json.loads((OUT/'protocol.json').read_text());selection=(OUT/'selection.json').read_bytes();index=json.loads((OUT/'archive-index.json').read_text())
 if sha(selection)!=protocol['selection_sha256']:raise ValueError('Selection changed')
 entries={e['name']:e for e in index['entries']};rows=json.loads(selection)['selection'];DEST.mkdir(parents=True,exist_ok=True);report=[]
 for i,row in enumerate(rows,1):
  entry=entries.get(row['member']);target=DEST/row['local_file']
  if not entry or entry['crc32']!=row['archive_crc32'] or entry['bytes']>1_000_000:raise ValueError('Unexpected archive image entry')
  data=fetch(entry)
  if target.exists() and target.read_bytes()!=data:raise ValueError('Previously downloaded tile differs')
  if not target.exists():target.write_bytes(data)
  report.append({'id':row['id'],'member':row['member'],'sha256':sha(data),'size':len(data)})
  print(f'{i}/{len(rows)} selected tiles verified',flush=True)
 (OUT/'download-report.json').write_text(json.dumps({'selection_sha256':sha(selection),'images':report},indent=2)+'\n')
 print('Frozen field retrieval complete.',flush=True)
if __name__=='__main__':main()
