#!/usr/bin/env python3
"""Rebuild this one-variant report in cb-allotment using frozen local caches."""
import argparse,hashlib,json,subprocess,sys
from pathlib import Path

def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--test-only',action='store_true');args=parser.parse_args()
    root=Path(__file__).resolve().parents[4]
    if not (root/'research/etf_rotation_holdings.py').is_file():parser.error('Run at the original cb-allotment repository path with local data caches.')
    if args.test_only:
        for pattern in ['test_etf_return20_study.py','test_etf_rotation_holdings.py']:
            subprocess.run([sys.executable,'-m','unittest','discover','-s','research','-p',pattern,'-v'],cwd=root,check=True)
        return
    manifest=json.loads(Path(__file__).with_name('input_manifest.json').read_text());changed=[]
    for name,record in manifest.items():
        file=root/name;expected=record['sha256'] if isinstance(record,dict) else record
        if not file.is_file() or hashlib.sha256(file.read_bytes()).hexdigest()!=expected:changed.append(name)
    if changed:parser.error('Frozen inputs changed/missing: '+', '.join(changed[:10]))
    variant=json.loads(Path(__file__).with_name('summary.json').read_text())['variant']
    subprocess.run([sys.executable,'research/etf_rotation_holdings.py','--variant',variant],cwd=root,check=True)
    subprocess.run([sys.executable,'research/build_etf_rotation_holdings_report.py'],cwd=root,check=True)

if __name__=='__main__':main()
