#!/usr/bin/env python3
"""Run inside cb-allotment with frozen local price/NAV caches. No raw data included."""
from pathlib import Path
import argparse,hashlib,json,subprocess,sys

def main():
 p=argparse.ArgumentParser(description=__doc__);p.add_argument('--test-only',action='store_true');p.add_argument('--allow-changed-inputs',action='store_true');args=p.parse_args()
 root=Path(__file__).resolve().parents[4]
 if not (root/'research/etf_hindsight_audit.py').is_file():p.error('Use the original report path inside cb-allotment.')
 if args.test_only:
  for pattern in ['test_etf_practical_optimization.py','test_etf_return20_study.py','test_etf_qdii_extension.py','test_etf_hindsight_audit.py']:
   subprocess.run([sys.executable,'-m','unittest','discover','-s','research','-p',pattern,'-v'],cwd=root,check=True)
 else:
  if not args.allow_changed_inputs:
   m=json.loads(Path(__file__).with_name('input_manifest.json').read_text());bad=[]
   for name,rec in m.items():
    f=root/name;expected=rec['sha256'] if isinstance(rec,dict) else rec
    if not f.is_file() or hashlib.sha256(f.read_bytes()).hexdigest()!=expected:bad.append(name)
   if bad:p.error('Frozen input missing/changed. Restore it or start a new experiment with --allow-changed-inputs: '+', '.join(bad[:10]))
  subprocess.run([sys.executable,'research/etf_hindsight_audit.py'],cwd=root,check=True)
  subprocess.run([sys.executable,'research/build_etf_hindsight_report.py'],cwd=root,check=True)
if __name__=='__main__':main()
