"""Verify reserved archive bytes and list ZIP directory, without decoding images."""
import hashlib,json,os,zipfile
from pathlib import Path
R=Path(__file__).resolve().parents[1];P=R/'datasets/r112-external-candidates/repod';policy=json.loads((P/'holdout-policy.json').read_text());partial=P/'stage2-images.zip.partial';final=P/'stage2-images.zip';report=P/'archive-verification.json'
audit_path=R/'results/r112/external-reference-sources/metadata-audit.json';meta_verify=R/'results/r112/external-reference-sources/metadata-verify.json';audit=json.loads(audit_path.read_text());verified=json.loads(meta_verify.read_text());assert policy['metadata_audit_sha256']==verified['metadata_audit_sha256']==hashlib.sha256(audit_path.read_bytes()).hexdigest() and verified['holdout_policy_sha256']==hashlib.sha256((P/'holdout-policy.json').read_bytes()).hexdigest();assert audit['repod']['archive_expected_bytes']==policy['stage2_archive_expected_bytes'] and audit['repod']['archive_published_md5']==policy['stage2_archive_published_md5']
assert not final.exists() and not report.exists() and partial.is_file();assert partial.stat().st_size==policy['stage2_archive_expected_bytes'];md5=hashlib.md5();sha=hashlib.sha256()
with partial.open('rb') as f:
 for block in iter(lambda:f.read(1024*1024),b''):md5.update(block);sha.update(block)
assert md5.hexdigest()==policy['stage2_archive_published_md5'];entries=[];names=set()
with zipfile.ZipFile(partial) as archive:
 for info in archive.infolist():
  name=info.filename
  if name in names or name.startswith('/') or '\\' in name or any(x in ('..','') for x in name.rstrip('/').split('/')):raise ValueError('Unsafe or duplicate archive entry')
  names.add(name);entries.append({'path':name,'compressed_bytes':info.compress_size,'uncompressed_bytes':info.file_size,'crc32':f'{info.CRC:08x}','directory':info.is_dir()})
assert entries;result={'format':'r112-repod-reserved-archive-v1','dataset_url':policy['source'],'archive_file':final.name,'bytes':partial.stat().st_size,'published_md5':policy['stage2_archive_published_md5'],'computed_md5':md5.hexdigest(),'computed_sha256':sha.hexdigest(),'verification_script_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),'holdout_policy_sha256':hashlib.sha256((P/'holdout-policy.json').read_bytes()).hexdigest(),'metadata_audit_sha256':policy['metadata_audit_sha256'],'entries':entries,'warning':'Archive is a reserved external candidate. This verifies full-archive bytes and ZIP central-directory structure only; image pixels, individual decompressed-member CRCs, labels, scientific independence and rights for derived use were not checked. No images were opened, used for model training, inference or visual selection.'}
os.replace(partial,final);temp=report.with_suffix('.json.tmp');temp.write_text(json.dumps(result,indent=2)+'\n');temp.replace(report);print(json.dumps({'bytes':result['bytes'],'computed_md5':result['computed_md5'],'computed_sha256':result['computed_sha256'],'directory_entries':len(entries)},indent=2))
