"""Compare public ZIP central directory to ledger without reading image pixels."""
import collections,csv,hashlib,json,zipfile
from pathlib import Path
from diatom_pilot.fetch_ude_adaptation import RemoteArchive,PREFIX,SIZE,URL
R=Path(__file__).resolve().parents[1];O=R/'results/r112/ude-sampling-metadata';L=O/'exposure-ledger.csv';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();rows=list(csv.DictReader(L.open()));wanted={PREFIX+x['cutout_filename']:x for x in rows};assert len(wanted)==len(rows)==83570
with zipfile.ZipFile(RemoteArchive()) as z:
 infos=z.infolist();groups=collections.Counter(x.filename for x in infos);mapping={x.filename:x for x in infos};missing=sorted(set(wanted)-set(mapping));duplicates=sorted(name for name in wanted if groups[name]>1);size_counts=collections.Counter();oversized=[];max_size=0
 for name,row in wanted.items():
  if name not in mapping:continue
  i=mapping[name];max_size=max(max_size,i.file_size);size_counts[row['exposure_status']]+=1
  if i.file_size>4*1024*1024:oversized.append({'annotation_id':row['annotation_id'],'size':i.file_size,'status':row['exposure_status']})
 result={'format':'r112-ude-remote-directory-v1','source':URL,'expected_archive_bytes':SIZE,'ledger_sha256':sha(L),'script_sha256':sha(Path(__file__)),'metadata_rows':len(rows),'zip_entries':len(infos),'matching_rows':sum(size_counts.values()),'matched_by_status':dict(size_counts),'missing_metadata_members':missing,'duplicate_wanted_member_names':duplicates,'largest_member_uncompressed_png_bytes':max_size,'over_4mib_count':len(oversized),'over_4mib':oversized,'limitations':'Remote ZIP central directory only; no image CRC, content, identities or sample grouping validated. Whole archive download remains unverified until published MD5 matches. Metadata and ZIP entries may change at the source.'};(O/'remote-directory.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps({k:result[k] for k in ('metadata_rows','zip_entries','matching_rows','largest_member_uncompressed_png_bytes','over_4mib_count')},indent=2),flush=True)
