#!/usr/bin/env python3
"""Mechanism diagnostics, not a trading backtest. Requires original frozen local data."""
import argparse,hashlib,json,subprocess,sys
from pathlib import Path
def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--test-only',action='store_true');args=p.parse_args()
    root=Path(__file__).resolve().parents[4]
    if not (root/'research/etf_mechanism_validation.py').is_file():p.error('Run at the original path in cb-allotment. Raw data are not bundled.')
    subprocess.run([sys.executable,'-m','unittest','discover','-s','research','-p','test_etf_mechanism_validation.py','-v'],cwd=root,check=True)
    if args.test_only:return
    manifest=json.loads(Path(__file__).with_name('input_manifest.json').read_text());changed=[]
    for name,record in manifest.items():
        file=root/name
        if not file.is_file():changed.append(name);continue
        h=hashlib.sha256()
        with file.open('rb') as f:
            for chunk in iter(lambda:f.read(1<<20),b''):h.update(chunk)
        if h.hexdigest()!=record['sha256']:changed.append(name)
    if changed:p.error('Frozen inputs changed/missing; restore the original files before reproducing: '+', '.join(changed))
    for script in ['etf_mechanism_validation.py','validate_etf_mechanism_validation.py','build_etf_mechanism_report.py']:
        subprocess.run([sys.executable,'research/'+script],cwd=root,check=True)
if __name__=='__main__':main()
