"""Replay source metadata indexing and check external reservation policy."""
import json,tempfile
from pathlib import Path
import r112_external_reference_metadata as source
R=Path(__file__).resolve().parents[1];O=R/'results/r112/external-reference-sources';P=R/'datasets/r112-external-candidates/repod';a=json.loads((O/'metadata-audit.json').read_text());policy=json.loads((P/'holdout-policy.json').read_text())
for f,h in a['inputs_sha256'].items():assert source.digest(R/f)==h,f
refs=a['repod']['reserved_stage2_records'];assert len(refs)==157 and len({x['image_id'] for x in refs})==157 and len([x for x in refs if x['source_group']=='Bacillariophyta'])==17;assert policy['metadata_audit_sha256']==source.digest(O/'metadata-audit.json') and policy['reserved_stage2_ids']==[f'{i:03d}' for i in range(1,158)] and policy['reserved_stage1_ids']==[f'Case{i:02d}' for i in range(1,31)] and all('reserved' in x['status'] for x in refs)
with tempfile.TemporaryDirectory(prefix='r112-external-replay-',dir='/tmp') as tmp:
 source.O=Path(tmp);source.main();assert (source.O/'metadata-audit.json').read_bytes()==(O/'metadata-audit.json').read_bytes()
report={'format':'r112-external-reference-metadata-verify-v1','metadata_audit_sha256':source.digest(O/'metadata-audit.json'),'holdout_policy_sha256':source.digest(P/'holdout-policy.json'),'reference_rows':len(refs),'diatom_rows':17,'checks':'All saved metadata hashes, downloaded README and workbook published MD5 values, unique Stage 2 IDs, reserved case lists and byte-identical metadata-only replay checked. Images have not been decoded by this audit. This does not establish data accessibility, taxonomic truth, independence or model novelty.'};(O/'metadata-verify.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
