"""
Intelligence Enhancements - Advanced intelligence layer integration

This module provides enhanced intelligence capabilities:
- Multi-source data fusion
- Advanced pattern recognition
- Predictive modeling
- Real-time intelligence updates
- Cross-module coordination
- Intelligence scoring system

Author: Pezhman Hajipour
Version: 2.7.4
"""

import logging
import asyncio
import numpy as np
from typing import Dict, List, Optional, Tuple, Any
from datetime import datetime, timedelta
from dataclasses import dataclass, field
from collections import defaultdict, deque
import statistics
import math
from concurrent.futures import ThreadPoolExecutor

from ..core_types import WhaleBotConfig, EnhancedTrade, FollowRecommendation, WhalePattern
from ..analysis import VolumeAnomalyDetector, CorrelationEngine
from ..risk import AdvancedRiskManager
from ..intelligence.sentiment_analyzer import SentimentScore, SentimentAnomaly

logger = logging.getLogger(__name__)

@dataclass
class IntelligenceSignal:
    """Comprehensive intelligence signal"""
    signal_id: str
    timestamp: datetime
    signal_type: str  # "WHALE_FOLLOW", "MARKET_ENTRY", "RISK_ALERT", "CORRELATION_TRADE"
    asset: str
    strength: float  # 0.0 to 1.0
    confidence: float  # 0.0 to 1.0
    components: Dict[str, float]  # Individual component scores
    recommendation: FollowRecommendation
    intelligence_sources: List[str]  # ["volume", "correlation", "sentiment", "risk"]
    market_context: Dict[str, Any]
    expected_duration: int  # Minutes

@dataclass
class IntelligenceSummary:
    """Comprehensive intelligence summary"""
    timestamp: datetime
    market_intelligence: Dict[str, float]
    whale_intelligence: Dict[str, Any]
    risk_intelligence: Dict[str, float]
    sentiment_intelligence: Dict[str, float]
    correlation_intelligence: Dict[str, float]
    volume_intelligence: Dict[str, float]
    overall_score: float
    top_signals: List[IntelligenceSignal]
    alerts: List[str]
    recommendations: List[str]

@dataclass
class PredictiveInsight:
    """Predictive market insight"""
    insight_type: str  # "PRICE_MOVEMENT", "VOLUME_SPIKE", "CORRELATION_SHIFT"
    prediction: str  # "UP", "DOWN", "SIDEWAYS", "VOLATILE"
    confidence: float
    timeframe: str  # "1H", "4H", "1D"
    probability: float
    supporting_evidence: List[str]
    historical_accuracy: float

class IntelligenceEnhancements:
    """
    Advanced intelligence enhancements system
    
    Features:
    - Multi-source data fusion
    - Advanced pattern recognition
    - Predictive modeling
    - Real-time intelligence coordination
    - Intelligence scoring and weighting
    - Cross-market analysis
    """
    
    def __init__(self, config: WhaleBotConfig):
        self.config = config
        
        # Initialize all intelligence components
        self.volume_detector = VolumeAnomalyDetector(config)
        self.correlation_engine = CorrelationEngine(config)
        self.risk_manager = AdvancedRiskManager(config)
        from ..intelligence.sentiment_analyzer import SocialSentimentAnalyzer
        self.sentiment_analyzer = SocialSentimentAnalyzer(config)
        
        # Intelligence tracking
        self.intelligence_signals: List[IntelligenceSignal] = []
        self.predictive_insights: List[PredictiveInsight] = []
        self.intelligence_history: deque = deque(maxlen=1000)
        
        # Intelligence scoring weights
        self.component_weights = {
            "volume": 0.25,
            "correlation": 0.20,
            "sentiment": 0.20,
            "risk": 0.15,
            "pattern": 0.20
        }
        
        # Signal thresholds
        self.min_signal_strength = 0.6
        self.high_confidence_threshold = 0.8
        self.urgent_signal_threshold = 0.9
        
        logger.info("IntelligenceEnhancements initialized with multi-source analysis")
    
    def set_monitor(self, monitor):
        """Set monitor for all components"""
        self.volume_detector.set_monitor(monitor)
        self.correlation_engine.set_monitor(monitor)
        self.risk_manager.set_monitor(monitor)
    
    async def generate_comprehensive_intelligence(self, trade: EnhancedTrade) -> IntelligenceSignal:
        """
        Generate comprehensive intelligence signal from a trade
        
        Args:
            trade: Whale trade to analyze
            
        Returns:
            IntelligenceSignal with multi-source analysis
        """
        try:
            # Run all intelligence analyses in parallel
            intelligence_tasks = await asyncio.gather(
                self._analyze_volume_intelligence(trade),
                self._analyze_correlation_intelligence(trade),
                self._analyze_sentiment_intelligence(trade),
                self._analyze_risk_intelligence(trade),
                self._analyze_pattern_intelligence(trade)
            )
            
            volume_intel, correlation_intel, sentiment_intel, risk_intel, pattern_intel = intelligence_tasks
            
            # Combine intelligence scores
            components = {
                "volume": volume_intel,
                "correlation": correlation_intel,
                "sentiment": sentiment_intel,
                "risk": risk_intel,
                "pattern": pattern_intel
            }
            
            # Calculate overall strength and confidence
            strength = self._calculate_signal_strength(components)
            confidence = self._calculate_signal_confidence(components, trade)
            
            # Generate recommendation
            recommendation = self._generate_intelligent_recommendation(
                trade, components, strength, confidence
            )
            
            # Determine signal type
            signal_type = self._classify_signal_type(components, strength)
            
            # Get market context
            market_context = await self._get_market_context(trade.coin)
            
            # Estimate duration
            expected_duration = self._estimate_signal_duration(components)
            
            # Generate signal ID
            signal_id = f"intel_{trade.coin}_{int(trade.timestamp.timestamp())}_{len(self.intelligence_signals)}"
            
            signal = IntelligenceSignal(
                signal_id=signal_id,
                timestamp=datetime.now(),
                signal_type=signal_type,
                asset=trade.coin,
                strength=strength,
                confidence=confidence,
                components=components,
                recommendation=recommendation,
                intelligence_sources=list(components.keys()),
                market_context=market_context,
                expected_duration=expected_duration
            )
            
            # Store signal
            self.intelligence_signals.append(signal)
            
            # Keep only recent signals
            if len(self.intelligence_signals) > 200:
                self.intelligence_signals = self.intelligence_signals[-200:]
            
            logger.info(f"Intelligence signal generated for {trade.coin}: {signal_type} "
                       f"(strength: {strength:.2f}, confidence: {confidence:.2f})")
            
            return signal
            
        except Exception as e:
            logger.error(f"Error generating comprehensive intelligence: {e}")
            return IntelligenceSignal(
                signal_id="error",
                timestamp=datetime.now(),
                signal_type="ERROR",
                asset=trade.coin,
                strength=0.0,
                confidence=0.0,
                components={},
                recommendation=FollowRecommendation("SKIP", 0.0, "Error in intelligence analysis", 60, 0.0, 0.0, []),
                intelligence_sources=[],
                market_context={},
                expected_duration=0
            )
    
    async def predict_market_movement(self, asset: str, timeframe: str = "1H") -> PredictiveInsight:
        """
        Predict market movement based on intelligence signals
        
        Args:
            asset: Asset symbol
            timeframe: Prediction timeframe
            
        Returns:
            PredictiveInsight with market prediction
        """
        try:
            # Get recent intelligence signals for asset
            recent_signals = [
                s for s in self.intelligence_signals[-50:] 
                if s.asset == asset and s.timestamp >= datetime.now() - timedelta(hours=4)
            ]
            
            if not recent_signals:
                return PredictiveInsight(
                    insight_type="INSUFFICIENT_DATA",
                    prediction="UNKNOWN",
                    confidence=0.0,
                    timeframe=timeframe,
                    probability=0.0,
                    supporting_evidence=[],
                    historical_accuracy=0.0
                )
            
            # Analyze signal patterns
            signal_patterns = self._analyze_signal_patterns(recent_signals)
            
            # Combine with market data
            market_intel = await self._get_market_intelligence(asset)
            sentiment_intel = await self.sentiment_analyzer.analyze_asset_sentiment(asset, timeframe)
            volume_intel = await self._get_volume_intelligence(asset)
            
            # Make prediction
            prediction_components = {
                "signal_strength": signal_patterns.get("avg_strength", 0.0),
                "sentiment": sentiment_intel.score,
                "volume": volume_intel.get("anomaly_score", 0.0),
                "correlation": market_intel.get("correlation_strength", 0.0),
                "risk": market_intel.get("risk_level", 0.0)
            }
            
            # Calculate prediction
            prediction, probability, confidence = self._calculate_market_prediction(
                prediction_components, recent_signals
            )
            
            # Generate supporting evidence
            evidence = self._generate_prediction_evidence(
                prediction_components, recent_signals, sentiment_intel
            )
            
            # Calculate historical accuracy (simulated)
            historical_accuracy = self._simulate_historical_accuracy(asset)
            
            insight = PredictiveInsight(
                insight_type="PRICE_MOVEMENT",
                prediction=prediction,
                confidence=confidence,
                timeframe=timeframe,
                probability=probability,
                supporting_evidence=evidence,
                historical_accuracy=historical_accuracy
            )
            
            # Store insight
            self.predictive_insights.append(insight)
            
            return insight
            
        except Exception as e:
            logger.error(f"Error predicting market movement for {asset}: {e}")
            return PredictiveInsight(
                insight_type="ERROR",
                prediction="UNKNOWN",
                confidence=0.0,
                timeframe=timeframe,
                probability=0.0,
                supporting_evidence=["analysis_error"],
                historical_accuracy=0.0
            )
    
    async def get_intelligence_summary(self) -> IntelligenceSummary:
        """
        Get comprehensive intelligence summary
        
        Returns:
            IntelligenceSummary with all intelligence metrics
        """
        try:
            # Get market intelligence
            market_intel = await self._get_market_intelligence_summary()
            
            # Get whale intelligence
            whale_intel = await self._get_whale_intelligence_summary()
            
            # Get risk intelligence
            risk_intel = await self._get_risk_intelligence_summary()
            
            # Get sentiment intelligence
            sentiment_intel = self.sentiment_analyzer.get_sentiment_summary()
            
            # Get correlation intelligence
            correlation_intel = self.correlation_engine.get_correlation_summary()
            
            # Get volume intelligence
            volume_intel = self.volume_detector.get_volume_anomalies_summary()
            
            # Calculate overall intelligence score
            overall_score = self._calculate_overall_intelligence_score({
                "market": market_intel,
                "whale": whale_intel,
                "risk": risk_intel,
                "sentiment": sentiment_intel,
                "correlation": correlation_intel,
                "volume": volume_intel
            })
            
            # Get top signals
            top_signals = sorted(
                self.intelligence_signals[-20:], 
                key=lambda s: s.strength * s.confidence, 
                reverse=True
            )[:5]
            
            # Generate alerts and recommendations
            alerts = self._generate_intelligence_alerts(market_intel, risk_intel, sentiment_intel)
            recommendations = self._generate_intelligence_recommendations(
                market_intel, whale_intel, risk_intel, sentiment_intel
            )
            
            return IntelligenceSummary(
                timestamp=datetime.now(),
                market_intelligence=market_intel,
                whale_intelligence=whale_intel,
                risk_intelligence=risk_intel,
                sentiment_intelligence=sentiment_intel,
                correlation_intelligence=correlation_intel,
                volume_intelligence=volume_intel,
                overall_score=overall_score,
                top_signals=top_signals,
                alerts=alerts,
                recommendations=recommendations
            )
            
        except Exception as e:
            logger.error(f"Error generating intelligence summary: {e}")
            return IntelligenceSummary(
                timestamp=datetime.now(),
                market_intelligence={},
                whale_intelligence={},
                risk_intelligence={},
                sentiment_intelligence={},
                correlation_intelligence={},
                volume_intelligence={},
                overall_score=0.0,
                top_signals=[],
                alerts=["INTELLIGENCE_ERROR"],
                recommendations=["CHECK_SYSTEM_STATUS"]
            )
    
    async def _analyze_volume_intelligence(self, trade: EnhancedTrade) -> float:
        """Analyze volume-based intelligence"""
        try:
            # Simulate volume analysis for the trade
            # In real implementation, would use actual volume data
            volume_score = min(1.0, trade.size_usd / 10000000)  # Max score for $10M+ trades
            return volume_score
        except Exception as e:
            logger.error(f"Error analyzing volume intelligence: {e}")
            return 0.0
    
    async def _analyze_correlation_intelligence(self, trade: EnhancedTrade) -> float:
        """Analyze correlation-based intelligence"""
        try:
            # Check if trade aligns with correlation patterns
            # Simulated correlation analysis
            correlation_score = 0.5  # Base score
            return correlation_score
        except Exception as e:
            logger.error(f"Error analyzing correlation intelligence: {e}")
            return 0.0
    
    async def _analyze_sentiment_intelligence(self, trade: EnhancedTrade) -> float:
        """Analyze sentiment-based intelligence"""
        try:
            # Get current sentiment for the asset
            sentiment = await self.sentiment_analyzer.analyze_asset_sentiment(trade.coin)
            
            # Score based on sentiment alignment with trade direction
            if trade.whale_direction == "LONG" and sentiment.score > 0.2:
                return min(1.0, 0.5 + sentiment.score)
            elif trade.whale_direction == "SHORT" and sentiment.score < -0.2:
                return min(1.0, 0.5 + abs(sentiment.score))
            else:
                return 0.3  # Neutral score for conflicting signals
            
        except Exception as e:
            logger.error(f"Error analyzing sentiment intelligence: {e}")
            return 0.0
    
    async def _analyze_risk_intelligence(self, trade: EnhancedTrade) -> float:
        """Analyze risk-based intelligence"""
        try:
            # Assess trade risk using risk manager
            from ..core_types import FollowRecommendation
            recommendation = FollowRecommendation(
                action="FOLLOW",
                confidence=0.7,
                reasoning="Risk analysis",
                optimal_entry_delay=30,
                position_size_ratio=0.1,
                stop_loss_ratio=0.02,
                take_profit_levels=[trade.price * 1.02]
            )
            
            trade_risk = await self.risk_manager.assess_trade_risk(trade, recommendation, {})
            
            # Lower risk scores are better for intelligence
            return max(0.0, 1.0 - trade_risk.total_risk)
            
        except Exception as e:
            logger.error(f"Error analyzing risk intelligence: {e}")
            return 0.0
    
    async def _analyze_pattern_intelligence(self, trade: EnhancedTrade) -> float:
        """Analyze pattern-based intelligence"""
        try:
            # Use existing pattern recognition
            pattern = await self.correlation_engine.analyze_trade(trade)
            
            if pattern:
                return pattern.confidence
            else:
                return 0.3  # Base score for no pattern
            
        except Exception as e:
            logger.error(f"Error analyzing pattern intelligence: {e}")
            return 0.0
    
    def _calculate_signal_strength(self, components: Dict[str, float]) -> float:
        """Calculate overall signal strength"""
        weighted_sum = sum(
            components[component] * weight 
            for component, weight in self.component_weights.items()
        )
        return min(1.0, max(0.0, weighted_sum))
    
    def _calculate_signal_confidence(self, components: Dict[str, float], trade: EnhancedTrade) -> float:
        """Calculate signal confidence"""
        # Base confidence on data consistency
        component_scores = list(components.values())
        consistency = 1.0 - (statistics.stdev(component_scores) / max(0.001, statistics.mean(component_scores)))
        
        # Boost confidence for large trades
        size_boost = min(0.2, trade.size_usd / 50000000)  # Up to 0.2 boost for $50M+ trades
        
        # Ensure minimum confidence
        confidence = max(0.1, consistency + size_boost)
        return min(1.0, confidence)
    
    def _generate_intelligent_recommendation(self, trade: EnhancedTrade, components: Dict[str, float],
                                           strength: float, confidence: float) -> FollowRecommendation:
        """Generate intelligent recommendation based on all components"""
        # Base recommendation from strength and confidence
        if strength >= 0.8 and confidence >= 0.7:
            action = "FOLLOW"
            confidence_score = min(0.9, strength * confidence)
        elif strength >= 0.6:
            action = "FOLLOW"
            confidence_score = strength * confidence * 0.8
        else:
            action = "SKIP"
            confidence_score = strength * 0.5
        
        # Adjust position size based on intelligence
        base_size_ratio = min(0.2, trade.size_usd / 10000000)  # Max 20% of whale size
        intelligence_boost = strength * 0.1
        position_size_ratio = min(0.3, base_size_ratio + intelligence_boost)
        
        # Adjust timing based on market conditions
        sentiment_component = components.get("sentiment", 0.0)
        if sentiment_component > 0.5:
            optimal_delay = 15  # Enter faster on positive sentiment
        elif sentiment_component < -0.3:
            optimal_delay = 60  # Wait longer on negative sentiment
        else:
            optimal_delay = 30
        
        # Generate reasoning
        reasoning_parts = []
        for component, score in components.items():
            if score > 0.6:
                reasoning_parts.append(f"{component.title()} ({score:.2f})")
        
        reasoning = f"Strong intelligence: {', '.join(reasoning_parts)}" if reasoning_parts else "Moderate intelligence"
        
        return FollowRecommendation(
            action=action,
            confidence=confidence_score,
            reasoning=reasoning,
            optimal_entry_delay=optimal_delay,
            position_size_ratio=position_size_ratio,
            stop_loss_ratio=0.02,
            take_profit_levels=[trade.price * 1.02, trade.price * 1.05, trade.price * 1.08]
        )
    
    def _classify_signal_type(self, components: Dict[str, float], strength: float) -> str:
        """Classify the type of intelligence signal"""
        if strength >= 0.9:
            return "HIGH_CONFIDENCE_WHALE_FOLLOW"
        elif components.get("volume", 0) > 0.8:
            return "VOLUME_DRIVEN_SIGNAL"
        elif components.get("sentiment", 0) > 0.7:
            return "SENTIMENT_DRIVEN_SIGNAL"
        elif components.get("correlation", 0) > 0.7:
            return "CORRELATION_SIGNAL"
        elif components.get("risk", 0) > 0.6:
            return "RISK_ADJUSTED_SIGNAL"
        else:
            return "BALANCED_SIGNAL"
    
    async def _get_market_context(self, asset: str) -> Dict[str, Any]:
        """Get current market context"""
        try:
            # Get market risk
            market_risk = await self.risk_manager.assess_market_risk()
            
            # Get market regime
            market_regime = await self.correlation_engine.identify_market_regime()
            
            # Get sentiment
            sentiment = await self.sentiment_analyzer.analyze_asset_sentiment(asset)
            
            return {
                "market_risk_level": market_risk.market_stress_score,
                "market_regime": market_regime.regime_type,
                "sentiment_level": sentiment.sentiment_level,
                "whale_activity": market_regime.whale_activity_level,
                "volatility_regime": "HIGH" if market_risk.volatility_level > 0.05 else "NORMAL"
            }
            
        except Exception as e:
            logger.error(f"Error getting market context: {e}")
            return {"error": "context_unavailable"}
    
    def _estimate_signal_duration(self, components: Dict[str, float]) -> int:
        """Estimate expected duration of signal in minutes"""
        base_duration = 60  # 1 hour base
        
        # Adjust based on intelligence components
        if components.get("volume", 0) > 0.8:
            base_duration += 30  # Volume signals last longer
        
        if components.get("sentiment", 0) > 0.7:
            base_duration += 20  # Sentiment signals have momentum
        
        if components.get("risk", 0) > 0.7:
            base_duration -= 20  # High-risk signals resolve faster
        
        return max(15, base_duration)  # Minimum 15 minutes
    
    def _analyze_signal_patterns(self, signals: List[IntelligenceSignal]) -> Dict[str, float]:
        """Analyze patterns in intelligence signals"""
        if not signals:
            return {}
        
        return {
            "avg_strength": statistics.mean([s.strength for s in signals]),
            "avg_confidence": statistics.mean([s.confidence for s in signals]),
            "signal_consistency": 1.0 - (statistics.stdev([s.strength for s in signals]) if len(signals) > 1 else 0),
            "recent_signals": len(signals),
            "dominant_type": max(set([s.signal_type for s in signals]), key=[s.signal_type for s in signals].count)
        }
    
    async def _get_market_intelligence(self, asset: str) -> Dict[str, float]:
        """Get market intelligence metrics"""
        # Simplified market intelligence
        return {
            "correlation_strength": 0.5,
            "risk_level": 0.3,
            "volatility": 0.04,
            "liquidity": 0.8
        }
    
    async def _get_volume_intelligence(self, asset: str) -> Dict[str, float]:
        """Get volume intelligence metrics"""
        # Simplified volume intelligence
        return {
            "anomaly_score": 0.3,
            "volume_trend": "STABLE",
            "liquidity_flow": "NEUTRAL"
        }
    
    def _calculate_market_prediction(self, components: Dict[str, float], 
                                   signals: List[IntelligenceSignal]) -> Tuple[str, float, float]:
        """Calculate market movement prediction"""
        # Combine components
        signal_strength = components.get("signal_strength", 0.0)
        sentiment_score = components.get("sentiment", 0.0)
        volume_score = components.get("volume", 0.0)
        
        # Determine prediction direction
        if sentiment_score > 0.3 and signal_strength > 0.5:
            prediction = "UP"
            probability = min(0.9, (sentiment_score + signal_strength) / 2)
        elif sentiment_score < -0.3 and signal_strength > 0.5:
            prediction = "DOWN"
            probability = min(0.9, (abs(sentiment_score) + signal_strength) / 2)
        elif volume_score > 0.7:
            prediction = "VOLATILE"
            probability = 0.7
        else:
            prediction = "SIDEWAYS"
            probability = 0.4
        
        # Calculate confidence
        confidence = min(1.0, signal_strength * 0.8 + volume_score * 0.2)
        
        return prediction, probability, confidence
    
    def _generate_prediction_evidence(self, components: Dict[str, float], 
                                    signals: List[IntelligenceSignal], 
                                    sentiment: SentimentScore) -> List[str]:
        """Generate evidence supporting prediction"""
        evidence = []
        
        if components.get("signal_strength", 0) > 0.7:
            evidence.append("Strong intelligence signal strength")
        
        if sentiment.score > 0.4:
            evidence.append(f"Positive sentiment ({sentiment.score:.2f})")
        elif sentiment.score < -0.4:
            evidence.append(f"Negative sentiment ({sentiment.score:.2f})")
        
        if len(signals) >= 3:
            evidence.append(f"Multiple signals ({len(signals)}) in timeframe")
        
        if components.get("volume", 0) > 0.6:
            evidence.append("Volume anomalies detected")
        
        return evidence
    
    def _simulate_historical_accuracy(self, asset: str) -> float:
        """Simulate historical prediction accuracy"""
        # In real implementation, would track actual prediction accuracy
        import random
        return random.uniform(0.6, 0.85)
    
    async def _get_market_intelligence_summary(self) -> Dict[str, float]:
        """Get market intelligence summary"""
        try:
            market_risk = await self.risk_manager.assess_market_risk()
            return {
                "market_stress_score": market_risk.market_stress_score,
                "volatility_level": market_risk.volatility_level,
                "correlation_spike": 1.0 if market_risk.correlation_spike else 0.0,
                "liquidity_score": 0.7,  # Simulated
                "regime_stability": 0.8
            }
        except Exception as e:
            logger.error(f"Error getting market intelligence: {e}")
            return {"error": 1.0}
    
    async def _get_whale_intelligence_summary(self) -> Dict[str, Any]:
        """Get whale intelligence summary"""
        # Recent signals analysis
        recent_signals = [s for s in self.intelligence_signals[-20:]]
        
        return {
            "active_whales": len(set(s.signal_id.split('_')[1] for s in recent_signals)),
            "avg_signal_strength": statistics.mean([s.strength for s in recent_signals]) if recent_signals else 0.0,
            "signal_frequency": len(recent_signals),
            "dominant_pattern": "FOLLOW" if recent_signals else "NONE"
        }
    
    async def _get_risk_intelligence_summary(self) -> Dict[str, float]:
        """Get risk intelligence summary"""
        try:
            risk_summary = self.risk_manager.get_risk_summary()
            return {
                "overall_risk_score": risk_summary.get("average_risk_score", 0.5),
                "drawdown_level": risk_summary.get("max_drawdown", 0.0),
                "alert_count": risk_summary.get("recent_alerts", 0),
                "position_risk": 0.3,  # Simulated
                "correlation_risk": 0.4   # Simulated
            }
        except Exception as e:
            logger.error(f"Error getting risk intelligence: {e}")
            return {"error": 1.0}
    
    def _calculate_overall_intelligence_score(self, intelligence_data: Dict[str, Dict[str, Any]]) -> float:
        """Calculate overall intelligence score"""
        scores = []
        
        # Market intelligence
        market = intelligence_data.get("market", {})
        if "market_stress_score" in market:
            scores.append(1.0 - market["market_stress_score"])  # Lower stress = higher intelligence
        
        # Risk intelligence
        risk = intelligence_data.get("risk", {})
        if "overall_risk_score" in risk:
            scores.append(1.0 - risk["overall_risk_score"])  # Lower risk = higher intelligence
        
        # Whale intelligence
        whale = intelligence_data.get("whale", {})
        if "avg_signal_strength" in whale:
            scores.append(whale["avg_signal_strength"])
        
        # Sentiment intelligence
        sentiment = intelligence_data.get("sentiment", {})
        if "overall_sentiment" in sentiment:
            scores.append(abs(sentiment["overall_sentiment"]))
        
        return statistics.mean(scores) if scores else 0.0
    
    def _generate_intelligence_alerts(self, market_intel: Dict[str, float], 
                                    risk_intel: Dict[str, float], 
                                    sentiment_intel: Dict[str, Any]) -> List[str]:
        """Generate intelligence-based alerts"""
        alerts = []
        
        # Market alerts
        if market_intel.get("market_stress_score", 0) > 0.8:
            alerts.append("HIGH_MARKET_STRESS")
        
        if risk_intel.get("alert_count", 0) > 3:
            alerts.append("MULTIPLE_RISK_ALERTS")
        
        # Sentiment alerts
        sentiment_score = sentiment_intel.get("overall_sentiment", 0)
        if abs(sentiment_score) > 0.8:
            alerts.append("EXTREME_SENTIMENT")
        
        return alerts
    
    def _generate_intelligence_recommendations(self, market_intel: Dict[str, float],
                                             whale_intel: Dict[str, Any],
                                             risk_intel: Dict[str, float],
                                             sentiment_intel: Dict[str, Any]) -> List[str]:
        """Generate intelligence-based recommendations"""
        recommendations = []
        
        # Risk-based recommendations
        if risk_intel.get("overall_risk_score", 0) > 0.7:
            recommendations.append("REDUCE_POSITION_SIZES")
        
        # Market-based recommendations
        if market_intel.get("market_stress_score", 0) > 0.6:
            recommendations.append("INCREASE_CASH_POSITION")
        
        # Signal-based recommendations
        signal_strength = whale_intel.get("avg_signal_strength", 0)
        if signal_strength > 0.7:
            recommendations.append("ACTIVE_WHALE_FOLLOWING")
        
        # Sentiment-based recommendations
        sentiment_score = sentiment_intel.get("overall_sentiment", 0)
        if sentiment_score > 0.5:
            recommendations.append("BULLISH_MARKET_POSTURE")
        elif sentiment_score < -0.5:
            recommendations.append("BEARISH_MARKET_POSTURE")
        
        return recommendations
    
    def reset_intelligence(self):
        """Reset all intelligence data"""
        self.intelligence_signals.clear()
        self.predictive_insights.clear()
        self.intelligence_history.clear()
        
        # Reset all components
        self.volume_detector.reset_statistics()
        self.correlation_engine.reset_analysis()
        self.risk_manager.reset_risk_data()
        self.sentiment_analyzer.reset_sentiment_data()
        
        logger.info("Intelligence system data reset")