"""
CCT Bitcoin Crash Prediction Validation
Compares Black Hole/Red Star predictions against real Bitcoin events
"""
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",  # 3 weeks before ATH
        "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, $1.9B liquidated",
        "severity": "CRITICAL"
    },
    {
        "name": "November 2025 Government 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, ETF outflows $272M/day",
        "severity": "EXTREME"
    },
    {
        "name": "January 2024 ETF Launch Rally",
        "date_start": "2024-04-08",  # Earliest data available
        "date_end": "2024-06-30",
        "description": "Post-ETF approval rally period, generally bullish uptrend",
        "severity": "BULLISH"
    },
    {
        "name": "August 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
# ============================================================
print("🔬 CCT Bitcoin Prediction Validation")
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 and run CCT predictor
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 silently
predictions = []
for idx in range(predictor.WINDOW, len(prices)):
    result = predictor.predict_event(prices, idx)
    predictions.append({
        'index': idx,
        'date': dates[idx],
        'prediction': result['prediction'],
        'Psi_Red': result['Psi_Red'],
        'confidence': result['confidence']
    })

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")

    # Find predictions in this window
    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']}")
        print(f"   Period: {event['date_start']} to {event['date_end']}")
        print(f"   Real event: {event['description']}")
        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()
    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}")
    print(f"     Min Ψ_Red:  {min_psi:.6f}")

    # Classification logic
    if event['severity'] in ['CRITICAL', 'EXTREME', 'HIGH']:
        # These are crash events - should show Black Hole dominance
        if bh_pct > 50:
            print(f"   ✅ HIT: CCT correctly predicted crash risk (BH: {bh_pct:.0f}%)")
            hits += 1
        elif bh_pct > 25:
            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':
        # These are bullish events - should show Red Star dominance
        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}%")
print(f"  Crash Detection Rate: {hits/(hits+misses)*100:.1f}%" if (hits+misses) > 0 else "  N/A")

# Compute returns for threshold analysis
returns = np.concatenate([[0], np.diff(prices) / prices[:-1]])

# ============================================================
# PSI_RED THRESHOLD ANALYSIS
# ============================================================
print(f"\n{'=' * 70}")
print(f"📈 Ψ_Red THRESHOLD ANALYSIS (Daily Drop Detection)")
print(f"{'=' * 70}")

# Align predictions with actual returns
# predictions start at index WINDOW, returns start at index 1
window = predictor.WINDOW
pred_returns = returns[window:window+len(pred_df)]  # Same length as predictions
all_psi = pred_df['Psi_Red'].values

for threshold_pct in [0.002, 0.003, 0.004, 0.005, 0.008, 0.01]:
    # Low Psi = Black Hole (crash risk), High Psi = Red Star (stable)
    predicted_crash = all_psi < threshold_pct
    actual_drop = np.abs(pred_returns) > 0.02  # 2%+ moves

    true_pos = np.sum(predicted_crash & (pred_returns < -0.02))
    false_pos = np.sum(predicted_crash & (pred_returns >= -0.02))
    false_neg = np.sum(~predicted_crash & (pred_returns < -0.02))
    true_neg = np.sum(~predicted_crash & (pred_returns >= -0.02))

    precision = true_pos / (true_pos + false_pos) if (true_pos + false_pos) > 0 else 0
    recall = true_pos / (true_pos + false_neg) if (true_pos + false_neg) > 0 else 0
    f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0

    print(f"\n  Ψ_Red threshold < {threshold_pct:.4f} → Black Hole")
    print(f"    True Positives:  {true_pos:4d} (correctly predicted >2% drops)")
    print(f"    False Positives: {false_pos:4d} (predicted crash, none occurred)")
    print(f"    False Negatives: {false_neg:4d} (missed >2% drops)")
    print(f"    Precision: {precision:.1%} | Recall: {recall:.1%} | F1: {f1:.1%}")
