"""
CCT Bitcoin Crash Prediction Validation (V2)
Passes full cumulative price history to properly detect sustained drawdowns
"""
import numpy as np
import pandas as pd
import yfinance as yf

# ============================================================
# KNOWN REAL-WORLD BTC EVENTS (from research)
# ============================================================
REAL_EVENTS = [
    {
        "name": "October 2025 Tariff Flash Crash",
        "date_start": "2025-09-15",
        "date_end": "2025-10-15",
        "description": "ATH $126K Oct 6, then 100% China tariffs, $19B liquidations, BTC $126K→$110K",
        "severity": "HIGH"
    },
    {
        "name": "October-November 2025 Bear Market",
        "date_start": "2025-10-01",
        "date_end": "2025-12-01",
        "description": "BTC falls below $90K, breaks 50-week MA, Death Cross Nov 16, $85K support breaks",
        "severity": "CRITICAL"
    },
    {
        "name": "November 2025 Gov Shutdown Liquidity Drought",
        "date_start": "2025-10-15",
        "date_end": "2025-12-15",
        "description": "43-day gov shutdown, TGA freeze, ETF outflows $3B, FinCEN vs Huione, DATCo implosion",
        "severity": "CRITICAL"
    },
    {
        "name": "February 2026 Crash to $60K",
        "date_start": "2026-01-15",
        "date_end": "2026-02-15",
        "description": "BTC drops 52% from ATH, plunges to $60K, $2B liquidations",
        "severity": "EXTREME"
    },
    {
        "name": "April-June 2024 Bullish Rally",
        "date_start": "2024-04-08",
        "date_end": "2024-06-30",
        "description": "Post-ETF approval rally period, generally bullish",
        "severity": "BULLISH"
    },
    {
        "name": "July-Sept 2025 ATH Run",
        "date_start": "2025-07-15",
        "date_end": "2025-09-01",
        "description": "BTC reaches ATH $124K+ on pro-crypto administration",
        "severity": "BULLISH"
    },
]

# ============================================================
# RUN CCT PREDICTIONS WITH FULL HISTORY
# ============================================================
print("🔬 CCT Bitcoin Prediction Validation (V2 - Full History)")
print("=" * 70)

# Fetch BTC data
print("\n📊 Fetching BTC-USD data (2y, 1d)...")
stock = yf.Ticker("BTC-USD")
df = stock.history(period="2y", interval="1d")
prices = df['Close'].values
dates = df.index
print(f"✓ Retrieved {len(prices)} data points from {dates[0].strftime('%Y-%m-%d')} to {dates[-1].strftime('%Y-%m-%d')}")

import sys
sys.path.insert(0, '/home/per/Documents/Universe as a Fractal')
from ex01 import CCT_MarketCrash_Predictor

predictor = CCT_MarketCrash_Predictor(
    trained_theta=0.7342,
    collapse_threshold=0.7,
    critical_escape_prob=0.2,
    window_size=14,
    prediction_horizon=5
)

# Run predictions with FULL cumulative history passed to drawdown
predictions = []
running_max = prices[0]

for idx in range(predictor.WINDOW, len(prices)):
    # Standard sliding window for CCT components
    start_idx = max(0, idx - predictor.WINDOW)
    window = prices[start_idx:idx + 1]

    # Full cumulative history for drawdown
    full_history = prices[:idx + 1]

    psi_result = predictor.compute_red_star_potential(window)

    # Override drawdown risk with full-history calculation
    full_dd_risk = predictor._compute_drawdown_risk(full_history)

    # Recompute Psi_Red with full-history drawdown (exponential suppression)
    Psi_Red_corrected = psi_result['P_esc'] * psi_result['entropy_indicator'] * psi_result['energy_term'] * np.exp(-5.0 * full_dd_risk)

    prediction = 'RED_STAR' if Psi_Red_corrected > 0.004 else 'BLACK_HOLE'
    confidence = min(Psi_Red_corrected / 0.02, 1.0) if prediction == 'RED_STAR' else max(0.5, 1.0 - Psi_Red_corrected / 0.004)

    predictions.append({
        'index': idx,
        'date': dates[idx],
        'prediction': prediction,
        'Psi_Red': Psi_Red_corrected,
        'Psi_Red_original': psi_result['Psi_Red'],
        'drawdown_risk': full_dd_risk,
        'confidence': confidence,
        'price': prices[idx]
    })

pred_df = pd.DataFrame(predictions)

# ============================================================
# VALIDATE AGAINST REAL EVENTS
# ============================================================
print("\n" + "=" * 70)
print("📋 VALIDATION: CCT Predictions vs Real BTC Events")
print("=" * 70)

hits = 0
misses = 0
false_alarms = 0

for event in REAL_EVENTS:
    start = pd.Timestamp(event["date_start"], tz="UTC")
    end = pd.Timestamp(event["date_end"], tz="UTC")

    mask = (pred_df['date'] >= start) & (pred_df['date'] <= end)
    event_preds = pred_df[mask]

    if len(event_preds) == 0:
        print(f"\n⚠️  NO DATA for: {event['name']}")
        misses += 1
        continue

    black_hole_count = len(event_preds[event_preds['prediction'] == 'BLACK_HOLE'])
    red_star_count = len(event_preds[event_preds['prediction'] == 'RED_STAR'])
    total = len(event_preds)
    bh_pct = black_hole_count / total * 100

    avg_psi = event_preds['Psi_Red'].mean()
    avg_dd = event_preds['drawdown_risk'].mean()
    min_psi = event_preds['Psi_Red'].min()

    print(f"\n{'─' * 70}")
    print(f"📌 EVENT: {event['name']}")
    print(f"   Period: {event['date_start']} to {event['date_end']}")
    print(f"   Real event: {event['description']}")
    print(f"   Severity: {event['severity']}")
    print(f"   CCT Predictions: {total} days analyzed")
    print(f"     Black Hole: {black_hole_count} ({bh_pct:.0f}%)")
    print(f"     Red Star:   {red_star_count} ({100-bh_pct:.0f}%)")
    print(f"     Avg Ψ_Red:  {avg_psi:.6f} | Avg DD Risk: {avg_dd:.1%}")
    print(f"     Min Ψ_Red:  {min_psi:.6f}")

    if event['severity'] in ['CRITICAL', 'EXTREME', 'HIGH']:
        if bh_pct > 50:
            print(f"   ✅ HIT: CCT correctly predicted crash risk (BH: {bh_pct:.0f}%)")
            hits += 1
        elif bh_pct > 15:
            print(f"   ⚠️  PARTIAL: Mixed signal (BH: {bh_pct:.0f}%) - some warning")
            hits += 0.5
        else:
            print(f"   ❌ MISS: CCT failed to predict crash (BH: {bh_pct:.0f}%)")
            misses += 1
    elif event['severity'] == 'BULLISH':
        if bh_pct < 30:
            print(f"   ✅ HIT: CCT correctly showed stability (BH: {bh_pct:.0f}%)")
            hits += 1
        elif bh_pct < 60:
            print(f"   ⚠️  PARTIAL: Mixed signal during rally (BH: {bh_pct:.0f}%)")
            hits += 0.5
        else:
            print(f"   ❌ FALSE ALARM: CCT predicted crash during rally (BH: {bh_pct:.0f}%)")
            false_alarms += 1

# ============================================================
# OVERALL ACCURACY
# ============================================================
total_events = len(REAL_EVENTS)
print(f"\n{'=' * 70}")
print(f"📊 OVERALL ACCURACY")
print(f"{'=' * 70}")
print(f"  Total Events Tested: {total_events}")
print(f"  Hits:                {hits}")
print(f"  Misses:              {misses}")
print(f"  False Alarms:        {false_alarms}")
print(f"  Accuracy:            {hits/total_events*100:.1f}%")
if (hits + misses) > 0:
    print(f"  Crash Detection Rate:  {hits/(hits+misses)*100:.1f}%")

# ============================================================
# MONTHLY BREAKDOWN
# ============================================================
print(f"\n{'=' * 70}")
print(f"📅 MONTHLY BLACK HOLE BREAKDOWN")
print(f"{'=' * 70}")
pred_df['month'] = pred_df['date'].dt.to_period('M')
monthly = pred_df.groupby('month').agg(
    total=('prediction', 'count'),
    bh_count=('prediction', lambda x: (x == 'BLACK_HOLE').sum()),
    avg_dd=('drawdown_risk', 'mean'),
    min_psi=('Psi_Red', 'min'),
    avg_price=('price', 'mean')
)
monthly['bh_pct'] = monthly['bh_count'] / monthly['total'] * 100

for month, row in monthly.iterrows():
    if row['bh_count'] > 0:
        print(f"  {month}: {int(row['bh_count'])}/{int(row['total'])} BH ({row['bh_pct']:.0f}%) "
              f"| Avg DD: {row['avg_dd']:.1%} | Min Ψ: {row['min_psi']:.6f} | Avg Price: ${row['avg_price']:,.0f}")
