"""Audit a frozen published model-book roster; this is not a strategy backtest.

python scripts/audit_modelbook.py --capture  # explicitly freeze current public cases
python scripts/audit_modelbook.py [path-to-downloaded-json]
Only the standard library is required. No prices are fetched or reconstructed.
"""
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SNAPSHOT = ROOT / 'backend/content/evidence/2026-11-01-modelbook-audit.json'
RULES = ('ema10', 'ema20', 'wema10', 'wema20')


def analyze(snapshot):
    cases = snapshot['cases']
    measured = [s for s in cases if s['simulation'] is not None]
    errors = []
    for s in cases:
        r = s['simulation']
        if not r:
            continue
        risk = r['entry'] - r['stop']
        if risk <= 0:
            errors.append(s['slug'] + ': nonpositive initial risk')
            continue
        for rule in RULES:
            x = r.get(rule)
            if not x:
                continue
            # Weekly dates identify Monday, not the execution instant. Compare
            # week labels with entry's Monday; daily dates compare directly.
            from datetime import date, timedelta
            entry = date.fromisoformat(r['entryDate'])
            earliest = entry - timedelta(days=entry.weekday()) if rule.startswith('w') else entry
            if date.fromisoformat(x['exitDate']) < earliest:
                errors.append(s['slug'] + ': exit precedes entry: ' + rule)
            # Stored exits have four decimals; R has two. Respect that precision.
            recomputed = (x['exit'] - r['entry']) / risk
            if abs(recomputed - x['R']) > 0.0051 + 0.000051 / risk:
                errors.append(s['slug'] + ': R arithmetic differs: ' + rule)
    result = {
        'published': len(cases), 'withSimulation': len(measured),
        'withoutSimulation': [s['slug'] for s in cases if not s['simulation']],
        'entryBeforeBreakoutWeek': sum(s['simulation']['entryDate'] < s['breakoutWeek'] for s in measured),
        'rules': {rule: {
            'available': sum(rule in s['simulation'] for s in measured),
            'negative': sum(s['simulation'][rule]['R'] < 0 for s in measured if rule in s['simulation']),
            'exitBeforePeakWeek': sum(s['simulation'][rule]['exitDate'] < s['peakWeek'] for s in measured if rule in s['simulation']),
        } for rule in RULES},
        'drawdownStartsAfterWeekly20Exit': sum(s['drawdownStart'] > s['simulation']['wema20']['exitDate'] for s in measured if 'wema20' in s['simulation']),
        'arithmeticOrDateErrors': errors,
    }
    return result


def capture():
    book = json.loads((ROOT / 'backend/content/model/studies.json').read_text(encoding='utf-8'))
    rbook = json.loads((ROOT / 'backend/content/model/rmultiple.json').read_text(encoding='utf-8'))['studies']
    published = {p.stem for p in ROOT.glob('model-*.html')}
    rows = []
    for s in sorted(book['studies'], key=lambda s: s['slug']):
        if s['slug'] not in published:
            continue
        raw = rbook.get(s['slug'])
        simulation = {k: raw[k] for k in ('entry', 'stop', 'entryDate', 'Rpct', 'peakR', *RULES) if k in raw} if raw else None
        rows.append(dict(slug=s['slug'], symbol=s['sym'], name=s['name'], market=s['market'],
                         pivot=s['pivot'], peakPrice=s['peakPrice'], advancePct=s['advance'],
                         breakoutWeek=s['breakout'], peakWeek=s['peak'], drawdownPct=s['shakeout'],
                         drawdownStart=s['shakeFrom'], drawdownEnd=s['shakeTo'], simulation=simulation))
    snapshot = dict(schemaVersion=1, captured='2026-11-01', priceDatasetGenerated=book['generated'],
                    source='Published Trend Screeners model-book records; historical price inputs attributed to Yahoo Finance.',
                    scope='All 69 cases publicly available on 2026-11-01, not the unpublished queue. Weekly dates are week-start labels.',
                    limitations='Selected winners, not a representative universe. Reproduces aggregates and stored R arithmetic only; does not independently reproduce the original entry/EMA detection, execution, costs, adjusted-price history or corporate causal claims.',
                    cases=rows)
    SNAPSHOT.write_text(json.dumps(snapshot, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
    return snapshot


if __name__ == '__main__':
    if '--capture' in sys.argv:
        data = capture()
    else:
        path = Path(sys.argv[1]) if len(sys.argv) > 1 else SNAPSHOT
        data = json.loads(path.read_text(encoding='utf-8'))
    result = analyze(data)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    if result['arithmeticOrDateErrors']:
        sys.exit(1)
