"""Cross-check reserved ZIP directory and reference IDs without decoding members."""
import hashlib,json,zipfile
from pathlib import Path
R=Path(__file__).resolve().parents[1];P=R/'datasets/r112-external-candidates/repod';O=R/'results/r112/external-reference-sources';a=json.loads((P/'archive-verification.json').read_text());policy=json.loads((P/'holdout-policy.json').read_text());meta=json.loads((O/'metadata-audit.json').read_text());path=P/a['archive_file'];assert path.is_file() and path.stat().st_size==a['bytes']==policy['stage2_archive_expected_bytes'];h=hashlib.sha256()
with path.open('rb') as f:
 for chunk in iter(lambda:f.read(1024*1024),b''):h.update(chunk)
assert h.hexdigest()==a['computed_sha256'] and a['computed_md5']==a['published_md5']==policy['stage2_archive_published_md5'];assert a['holdout_policy_sha256']==hashlib.sha256((P/'holdout-policy.json').read_bytes()).hexdigest();entries=[]
with zipfile.ZipFile(path) as z:
 for i in z.infolist():entries.append({'path':i.filename,'compressed_bytes':i.compress_size,'uncompressed_bytes':i.file_size,'crc32':f'{i.CRC:08x}','directory':i.is_dir()})
assert entries==a['entries'];images={Path(x['path']).stem for x in entries if not x['directory'] and Path(x['path']).suffix.lower()=='.png'};assert images==set(policy['reserved_stage2_ids'])=={x['image_id'] for x in meta['repod']['reserved_stage2_records']};report={'format':'r112-repod-reserved-directory-verify-v1','archive_verification_sha256':hashlib.sha256((P/'archive-verification.json').read_bytes()).hexdigest(),'archive_sha256':h.hexdigest(),'directory_entries':len(entries),'png_entries':len(images),'reserved_ids_matched':len(images),'checks':'Full archive SHA-256 replayed, central directory re-enumerated and all 157 PNG member names matched to reserved metadata IDs. No compressed member was extracted or decoded; member CRCs, labels, scientific independence, exposure and license suitability are not validated.'};(P/'archive-directory-verify.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
