#!/usr/bin/env python3
"""Reproduce inside cb-allotment using frozen local caches; raw data excluded."""
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');a=p.parse_args();root=Path(__file__).resolve().parents[4]
 if not (root/'research/etf_ashare_sector_vol.py').is_file():p.error('Run at the original report path inside cb-allotment.')
 if a.test_only:
  for name in ['practical_optimization','return20_study','qdii_extension','hindsight_audit','ashare_sector_vol']:
   subprocess.run([sys.executable,'-m','unittest','discover','-s','research','-p','test_etf_'+name+'.py','-v'],cwd=root,check=True)
 else:
  if not a.allow_changed_inputs:
   bad=[]
   for name,rec in json.loads(Path(__file__).with_name('input_manifest.json').read_text()).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 inputs missing or changed: '+', '.join(bad[:10]))
  subprocess.run([sys.executable,'research/etf_ashare_sector_vol.py'],cwd=root,check=True)
  subprocess.run([sys.executable,'research/build_etf_ashare_sector_vol_report.py'],cwd=root,check=True)
if __name__=='__main__':main()
