"""
Advanced Risk Manager - Sophisticated risk management for whale tracking

This module provides advanced risk management capabilities:
- Dynamic position sizing based on market conditions
- Portfolio-level risk assessment
- Correlation risk monitoring
- Drawdown protection
- Real-time risk scoring
- Multi-timeframe risk analysis

Author: Pezhman Hajipour
Version: 2.7.4
"""

import logging
import numpy as np
import asyncio
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
from ..monitor import HyperliquidMonitor

logger = logging.getLogger(__name__)

@dataclass
class RiskMetrics:
    """Risk metrics for position and portfolio assessment"""
    portfolio_value: float
    position_risk: float  # Risk for individual position
    portfolio_risk: float  # Overall portfolio risk
    correlation_risk: float  # Risk from asset correlations
    volatility_risk: float  # Risk from market volatility
    liquidity_risk: float  # Risk from liquidity constraints
    total_risk_score: float  # 0.0 to 1.0
    risk_level: str  # "LOW", "MEDIUM", "HIGH", "CRITICAL"
    recommended_actions: List[str]

@dataclass
class PositionRisk:
    """Individual position risk analysis"""
    symbol: str
    position_size: float
    entry_price: float
    current_price: float
    unrealized_pnl: float
    risk_percentage: float
    correlation_risk: float
    volatility_risk: float
    liquidity_risk: float
    total_risk: float
    max_drawdown_risk: float
    recommendation: str  # "HOLD", "REDUCE", "CLOSE", "INCREASE"

@dataclass
class MarketRisk:
    """Overall market risk assessment"""
    market_regime: str
    volatility_level: float
    correlation_spike: bool
    liquidity_conditions: str  # "GOOD", "MODERATE", "POOR"
    whale_activity_level: str
    risk_factors: List[str]
    market_stress_score: float  # 0.0 to 1.0
    recommended_aggression: float  # 0.0 to 1.0

@dataclass
class RiskAlert:
    """Risk alert for critical situations"""
    alert_type: str  # "HIGH_RISK", "DRAWDOWN", "CORRELATION_SPIKE"
    severity: str  # "WARNING", "CRITICAL", "EMERGENCY"
    message: str
    recommended_action: str
    timestamp: datetime
    affected_positions: List[str]
    risk_metrics: RiskMetrics

class AdvancedRiskManager:
    """
    Advanced risk management system for whale tracking
    
    Features:
    - Real-time risk monitoring
    - Dynamic position sizing
    - Portfolio-level risk assessment
    - Correlation risk analysis
    - Drawdown protection
    - Multi-timeframe risk analysis
    """
    
    def __init__(self, config: WhaleBotConfig):
        self.config = config
        self.monitor = None  # Will be set by bot core
        
        # Risk tracking
        self.portfolio_history: deque = deque(maxlen=1000)
        self.position_risks: Dict[str, PositionRisk] = {}
        self.risk_alerts: List[RiskAlert] = []
        self.max_drawdown = 0.0
        self.peak_portfolio_value = 0.0
        
        # Risk parameters
        self.max_position_risk = config.max_position_risk
        self.max_portfolio_risk = 0.15  # 15% max portfolio risk
        self.max_correlation_exposure = 0.3  # 30% max exposure to correlated assets
        self.risk_free_rate = 0.02  # 2% risk-free rate
        
        # Market data for risk calculation
        self.volatility_data: Dict[str, deque] = defaultdict(lambda: deque(maxlen=100))
        self.correlation_matrix: Dict[str, Dict[str, float]] = {}
        self.liquidity_scores: Dict[str, float] = {}
        
        # Risk thresholds
        self.critical_risk_threshold = 0.8
        self.high_risk_threshold = 0.6
        self.medium_risk_threshold = 0.4
        
        logger.info(f"AdvancedRiskManager initialized with {self.max_position_risk} max position risk")
    
    def set_monitor(self, monitor: HyperliquidMonitor):
        """Set the monitor instance for real-time data"""
        self.monitor = monitor
    
    async def assess_portfolio_risk(self, positions: Dict[str, float], 
                                   portfolio_value: float) -> RiskMetrics:
        """
        Assess overall portfolio risk
        
        Args:
            positions: Dictionary of position symbols and values
            portfolio_value: Total portfolio value
            
        Returns:
            RiskMetrics with comprehensive risk assessment
        """
        try:
            # Update portfolio tracking
            self._update_portfolio_tracking(portfolio_value)
            
            # Calculate individual position risks
            individual_risks = []
            for symbol, position_value in positions.items():
                risk = await self._calculate_position_risk(symbol, position_value, portfolio_value)
                individual_risks.append(risk)
                self.position_risks[symbol] = risk
            
            # Calculate portfolio-level risks
            portfolio_risk = self._calculate_portfolio_risk(positions, portfolio_value)
            correlation_risk = self._calculate_correlation_risk(positions)
            volatility_risk = self._calculate_volatility_risk(positions)
            liquidity_risk = self._calculate_liquidity_risk(positions)
            
            # Calculate total risk score
            total_risk = self._calculate_total_risk(
                portfolio_risk, correlation_risk, volatility_risk, liquidity_risk
            )
            
            # Determine risk level
            risk_level = self._classify_risk_level(total_risk)
            
            # Generate recommendations
            recommendations = self._generate_risk_recommendations(
                individual_risks, total_risk, risk_level
            )
            
            # Check for risk alerts
            await self._check_risk_alerts(total_risk, risk_level, positions)
            
            metrics = RiskMetrics(
                portfolio_value=portfolio_value,
                position_risk=statistics.mean([r.risk_percentage for r in individual_risks]) if individual_risks else 0.0,
                portfolio_risk=portfolio_risk,
                correlation_risk=correlation_risk,
                volatility_risk=volatility_risk,
                liquidity_risk=liquidity_risk,
                total_risk_score=total_risk,
                risk_level=risk_level,
                recommended_actions=recommendations
            )
            
            return metrics
            
        except Exception as e:
            logger.error(f"Error assessing portfolio risk: {e}")
            return RiskMetrics(
                portfolio_value=portfolio_value,
                position_risk=0.0,
                portfolio_risk=0.0,
                correlation_risk=0.0,
                volatility_risk=0.0,
                liquidity_risk=0.0,
                total_risk_score=1.0,
                risk_level="CRITICAL",
                recommended_actions=["ERROR_RISK_ASSESSMENT"]
            )
    
    async def calculate_optimal_position_size(self, trade: EnhancedTrade, 
                                           recommendation: FollowRecommendation,
                                           portfolio_value: float,
                                           positions: Dict[str, float]) -> float:
        """
        Calculate optimal position size based on risk management rules
        
        Args:
            trade: The trade to be executed
            recommendation: Follow recommendation from whale analysis
            portfolio_value: Current portfolio value
            existing_positions: Current portfolio positions
            
        Returns:
            Optimal position size adjusted for risk
        """
        try:
            # Base position size from recommendation
            base_size = recommendation.position_size_ratio * trade.size_usd
            
            # Risk-adjusted sizing
            position_risk = await self._calculate_position_risk(
                trade.coin, base_size, portfolio_value
            )
            
            # Apply risk constraints
            max_size = self._calculate_max_position_size(portfolio_value)
            
            # Correlation adjustment
            correlation_factor = self._calculate_correlation_factor(trade.coin, positions)
            
            # Volatility adjustment
            volatility_factor = self._calculate_volatility_factor(trade.coin)
            
            # Market conditions factor
            market_factor = await self._calculate_market_factor()
            
            # Calculate optimal size
            optimal_size = base_size * correlation_factor * volatility_factor * market_factor
            
            # Apply risk limits
            optimal_size = min(optimal_size, max_size)
            
            # Ensure minimum viable size
            min_size = self.config.min_whale_threshold * 0.01  # 1% of whale threshold
            optimal_size = max(optimal_size, min_size)
            
            logger.info(f"Optimal position size for {trade.coin}: ${optimal_size:,.0f} "
                       f"(base: ${base_size:,.0f}, risk-adjusted)")
            
            return optimal_size
            
        except Exception as e:
            logger.error(f"Error calculating optimal position size for {trade.coin}: {e}")
            return 0.0
    
    async def assess_trade_risk(self, trade: EnhancedTrade, 
                              recommendation: FollowRecommendation,
                              portfolio_positions: Dict[str, float]) -> PositionRisk:
        """
        Assess risk for a specific trade
        
        Args:
            trade: Trade to assess
            recommendation: Follow recommendation
            existing_positions: Current portfolio positions
            
        Returns:
            PositionRisk analysis for the trade
        """
        try:
            # Calculate position metrics
            position_size = recommendation.position_size_ratio * trade.size_usd
            entry_price = trade.price
            
            # Calculate risk components
            volatility_risk = self._calculate_volatility_risk_component(trade.coin)
            correlation_risk = self._calculate_correlation_risk_component(trade.coin, portfolio_positions)
            liquidity_risk = self._calculate_liquidity_risk_component(trade.coin, position_size)
            
            # Calculate total position risk
            total_risk = self._combine_risk_components(
                volatility_risk, correlation_risk, liquidity_risk
            )
            
            # Estimate max drawdown risk
            max_drawdown_risk = self._estimate_max_drawdown_risk(trade, position_size)
            
            # Generate recommendation
            recommendation_str = self._generate_trade_recommendation(total_risk, max_drawdown_risk)
            
            return PositionRisk(
                symbol=trade.coin,
                position_size=position_size,
                entry_price=entry_price,
                current_price=entry_price,  # Assuming no price change yet
                unrealized_pnl=0.0,
                risk_percentage=total_risk,
                correlation_risk=correlation_risk,
                volatility_risk=volatility_risk,
                liquidity_risk=liquidity_risk,
                total_risk=total_risk,
                max_drawdown_risk=max_drawdown_risk,
                recommendation=recommendation_str
            )
            
        except Exception as e:
            logger.error(f"Error assessing trade risk for {trade.coin}: {e}")
            return PositionRisk(
                symbol=trade.coin,
                position_size=0.0,
                entry_price=0.0,
                current_price=0.0,
                unrealized_pnl=0.0,
                risk_percentage=1.0,
                correlation_risk=1.0,
                volatility_risk=1.0,
                liquidity_risk=1.0,
                total_risk=1.0,
                max_drawdown_risk=1.0,
                recommendation="AVOID"
            )
    
    async def assess_market_risk(self) -> MarketRisk:
        """
        Assess overall market risk conditions
        
        Returns:
            MarketRisk with market condition analysis
        """
        try:
            # Assess market volatility
            volatility_level = self._calculate_market_volatility_level()
            
            # Check for correlation spikes
            correlation_spike = self._detect_correlation_spike()
            
            # Assess liquidity conditions
            liquidity_conditions = self._assess_liquidity_conditions()
            
            # Check whale activity
            whale_activity = self._assess_whale_activity_risk()
            
            # Identify risk factors
            risk_factors = self._identify_market_risk_factors(
                volatility_level, correlation_spike, liquidity_conditions
            )
            
            # Calculate market stress score
            stress_score = self._calculate_market_stress_score(
                volatility_level, correlation_spike, liquidity_conditions, whale_activity
            )
            
            # Determine market regime
            market_regime = self._determine_market_regime(stress_score)
            
            # Calculate recommended aggression level
            recommended_aggression = self._calculate_recommended_aggression(stress_score)
            
            return MarketRisk(
                market_regime=market_regime,
                volatility_level=volatility_level,
                correlation_spike=correlation_spike,
                liquidity_conditions=liquidity_conditions,
                whale_activity_level=whale_activity,
                risk_factors=risk_factors,
                market_stress_score=stress_score,
                recommended_aggression=recommended_aggression
            )
            
        except Exception as e:
            logger.error(f"Error assessing market risk: {e}")
            return MarketRisk(
                market_regime="UNKNOWN",
                volatility_level=1.0,
                correlation_spike=True,
                liquidity_conditions="POOR",
                whale_activity_level="HIGH",
                risk_factors=["ASSESSMENT_ERROR"],
                market_stress_score=1.0,
                recommended_aggression=0.0
            )
    
    def _update_portfolio_tracking(self, current_value: float):
        """Update portfolio tracking for drawdown analysis"""
        self.portfolio_history.append({
            'timestamp': datetime.now(),
            'value': current_value
        })
        
        # Update peak value
        if current_value > self.peak_portfolio_value:
            self.peak_portfolio_value = current_value
        
        # Update max drawdown
        if self.peak_portfolio_value > 0:
            drawdown = (self.peak_portfolio_value - current_value) / self.peak_portfolio_value
            self.max_drawdown = max(self.max_drawdown, drawdown)
    
    async def _calculate_position_risk(self, symbol: str, position_value: float, 
                                     portfolio_value: float) -> PositionRisk:
        """Calculate risk for individual position"""
        try:
            # Basic position risk
            position_percentage = position_value / portfolio_value
            
            # Volatility component
            volatility = self.volatility_data.get(symbol, deque())
            volatility_risk = 0.0
            if volatility:
                recent_volatility = statistics.mean(list(volatility)[-10:]) if len(volatility) > 10 else 0.0
                volatility_risk = min(1.0, recent_volatility * 10)  # Scale volatility
            
            # Correlation component
            correlation_risk = self._calculate_position_correlation_risk(symbol)
            
            # Liquidity component
            liquidity_score = self.liquidity_scores.get(symbol, 0.5)
            liquidity_risk = 1.0 - liquidity_score
            
            # Total risk
            total_risk = (position_percentage + volatility_risk + correlation_risk + liquidity_risk) / 4
            
            return PositionRisk(
                symbol=symbol,
                position_size=position_value,
                entry_price=0.0,  # Would be calculated from trade data
                current_price=0.0,
                unrealized_pnl=0.0,
                risk_percentage=position_percentage,
                correlation_risk=correlation_risk,
                volatility_risk=volatility_risk,
                liquidity_risk=liquidity_risk,
                total_risk=total_risk,
                max_drawdown_risk=total_risk * 1.5,
                recommendation="HOLD"
            )
            
        except Exception as e:
            logger.error(f"Error calculating position risk for {symbol}: {e}")
            return PositionRisk(symbol, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, "AVOID")
    
    def _calculate_portfolio_risk(self, positions: Dict[str, float], portfolio_value: float) -> float:
        """Calculate overall portfolio risk"""
        if portfolio_value <= 0:
            return 1.0
        
        # Individual position risks
        position_risks = []
        for symbol, value in positions.items():
            if symbol in self.position_risks:
                position_risks.append(self.position_risks[symbol].total_risk)
        
        if not position_risks:
            return 0.0
        
        # Portfolio diversification factor
        diversification_factor = self._calculate_diversification_factor(positions)
        
        # Weighted average risk
        weighted_risk = statistics.mean(position_risks)
        
        # Apply diversification
        portfolio_risk = weighted_risk * (1.0 - diversification_factor * 0.3)
        
        return min(1.0, portfolio_risk)
    
    def _calculate_correlation_risk(self, positions: Dict[str, float]) -> float:
        """Calculate correlation risk for portfolio"""
        symbols = list(positions.keys())
        if len(symbols) < 2:
            return 0.0
        
        # Calculate average correlation
        correlations = []
        for i, symbol1 in enumerate(symbols):
            for symbol2 in symbols[i+1:]:
                correlation = self.correlation_matrix.get(symbol1, {}).get(symbol2, 0.0)
                correlations.append(abs(correlation))
        
        if not correlations:
            return 0.0
        
        # Risk increases with correlation
        avg_correlation = statistics.mean(correlations)
        correlation_risk = min(1.0, avg_correlation)
        
        return correlation_risk
    
    def _calculate_volatility_risk(self, positions: Dict[str, float]) -> float:
        """Calculate volatility risk for portfolio"""
        volatilities = []
        
        for symbol in positions.keys():
            vol_data = self.volatility_data.get(symbol, deque())
            if vol_data:
                recent_vol = statistics.mean(list(vol_data)[-5:]) if len(vol_data) > 5 else 0.0
                volatilities.append(recent_vol)
        
        if not volatilities:
            return 0.0
        
        avg_volatility = statistics.mean(volatilities)
        return min(1.0, avg_volatility * 20)  # Scale volatility
    
    def _calculate_liquidity_risk(self, positions: Dict[str, float]) -> float:
        """Calculate liquidity risk for portfolio"""
        liquidity_risks = []
        
        for symbol, value in positions.items():
            liquidity_score = self.liquidity_scores.get(symbol, 0.5)
            position_risk = min(1.0, value / 1000000)  # Higher risk for larger positions
            liquidity_risk = (1.0 - liquidity_score) * position_risk
            liquidity_risks.append(liquidity_risk)
        
        return statistics.mean(liquidity_risks) if liquidity_risks else 0.0
    
    def _calculate_total_risk(self, portfolio_risk: float, correlation_risk: float,
                            volatility_risk: float, liquidity_risk: float) -> float:
        """Calculate total risk score"""
        # Weighted combination of risk components
        weights = {
            'portfolio': 0.4,
            'correlation': 0.25,
            'volatility': 0.25,
            'liquidity': 0.1
        }
        
        total = (portfolio_risk * weights['portfolio'] +
                correlation_risk * weights['correlation'] +
                volatility_risk * weights['volatility'] +
                liquidity_risk * weights['liquidity'])
        
        return min(1.0, max(0.0, total))
    
    def _classify_risk_level(self, total_risk: float) -> str:
        """Classify risk level based on total risk score"""
        if total_risk >= self.critical_risk_threshold:
            return "CRITICAL"
        elif total_risk >= self.high_risk_threshold:
            return "HIGH"
        elif total_risk >= self.medium_risk_threshold:
            return "MEDIUM"
        else:
            return "LOW"
    
    def _generate_risk_recommendations(self, position_risks: List[PositionRisk],
                                     total_risk: float, risk_level: str) -> List[str]:
        """Generate risk management recommendations"""
        recommendations = []
        
        if risk_level == "CRITICAL":
            recommendations.extend([
                "REDUCE_ALL_POSITIONS",
                "INCREASE_CASH_POSITION",
                "STOP_NEW_TRADES"
            ])
        elif risk_level == "HIGH":
            recommendations.extend([
                "REDUCE_HIGH_RISK_POSITIONS",
                "DIVERSIFY_PORTFOLIO"
            ])
        elif risk_level == "MEDIUM":
            recommendations.append("MONITOR_POSITIONS_CLOSELY")
        else:
            recommendations.append("MAINTAIN_CURRENT_ALLOCATION")
        
        # Individual position recommendations
        for position_risk in position_risks:
            if position_risk.total_risk > 0.8:
                recommendations.append(f"CLOSE_{position_risk.symbol}")
            elif position_risk.total_risk > 0.6:
                recommendations.append(f"REDUCE_{position_risk.symbol}")
        
        return recommendations
    
    async def _check_risk_alerts(self, total_risk: float, risk_level: str, positions: Dict[str, float]):
        """Check for risk alerts and create if needed"""
        if risk_level == "CRITICAL" and total_risk > 0.9:
            alert = RiskAlert(
                alert_type="HIGH_RISK",
                severity="EMERGENCY",
                message=f"Portfolio risk critically high: {total_risk:.2f}",
                recommended_action="IMMEDIATE_ACTION_REQUIRED",
                timestamp=datetime.now(),
                affected_positions=list(positions.keys()),
                risk_metrics=RiskMetrics(
                    portfolio_value=sum(positions.values()),
                    position_risk=0.0,
                    portfolio_risk=total_risk,
                    correlation_risk=0.0,
                    volatility_risk=0.0,
                    liquidity_risk=0.0,
                    total_risk_score=total_risk,
                    risk_level=risk_level,
                    recommended_actions=[]
                )
            )
            self.risk_alerts.append(alert)
            logger.warning(f"CRITICAL RISK ALERT: {alert.message}")
        
        # Check for drawdown alerts
        if self.max_drawdown > 0.15:  # 15% drawdown threshold
            alert = RiskAlert(
                alert_type="DRAWDOWN",
                severity="CRITICAL",
                message=f"Portfolio drawdown: {self.max_drawdown:.1%}",
                recommended_action="IMPLEMENT_DRAWDOWN_PROTECTION",
                timestamp=datetime.now(),
                affected_positions=list(positions.keys()),
                risk_metrics=RiskMetrics(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, risk_level, [])
            )
            self.risk_alerts.append(alert)
    
    def _calculate_max_position_size(self, portfolio_value: float) -> float:
        """Calculate maximum allowed position size"""
        max_risk_amount = portfolio_value * self.max_position_risk
        return max_risk_amount
    
    def _calculate_correlation_factor(self, symbol: str, positions: Dict[str, float]) -> float:
        """Calculate correlation adjustment factor"""
        # Reduce size for highly correlated positions
        correlations = []
        for existing_symbol in positions.keys():
            if existing_symbol != symbol:
                correlation = self.correlation_matrix.get(symbol, {}).get(existing_symbol, 0.0)
                correlations.append(abs(correlation))
        
        if not correlations:
            return 1.0
        
        avg_correlation = statistics.mean(correlations)
        
        # Reduce position size for high correlation
        correlation_factor = max(0.3, 1.0 - avg_correlation * 0.5)
        
        return correlation_factor
    
    def _calculate_volatility_factor(self, symbol: str) -> float:
        """Calculate volatility adjustment factor"""
        vol_data = self.volatility_data.get(symbol, deque())
        if not vol_data:
            return 1.0
        
        recent_vol = statistics.mean(list(vol_data)[-5:]) if len(vol_data) > 5 else 0.0
        
        # Reduce position size for high volatility
        volatility_factor = max(0.1, 1.0 - recent_vol * 5)
        
        return volatility_factor
    
    async def _calculate_market_factor(self) -> float:
        """Calculate market conditions adjustment factor"""
        market_risk = await self.assess_market_risk()
        
        # Reduce aggression in high-risk markets
        market_factor = 1.0 - (market_risk.market_stress_score * 0.5)
        
        return max(0.1, market_factor)
    
    def update_volatility_data(self, symbol: str, volatility: float):
        """Update volatility data for risk calculations"""
        self.volatility_data[symbol].append(volatility)
    
    def update_correlation_data(self, symbol1: str, symbol2: str, correlation: float):
        """Update correlation matrix"""
        if symbol1 not in self.correlation_matrix:
            self.correlation_matrix[symbol1] = {}
        if symbol2 not in self.correlation_matrix:
            self.correlation_matrix[symbol2] = {}
        
        self.correlation_matrix[symbol1][symbol2] = correlation
        self.correlation_matrix[symbol2][symbol1] = correlation
    
    def update_liquidity_score(self, symbol: str, liquidity_score: float):
        """Update liquidity score for symbol"""
        self.liquidity_scores[symbol] = liquidity_score
    
    def get_risk_summary(self, hours_back: int = 24) -> Dict[str, Any]:
        """Get risk management summary"""
        cutoff_time = datetime.now() - timedelta(hours=hours_back)
        recent_alerts = [a for a in self.risk_alerts if a.timestamp >= cutoff_time]
        
        # Current risk metrics
        current_positions = list(self.position_risks.keys())
        avg_risk = statistics.mean([r.total_risk for r in self.position_risks.values()]) if self.position_risks else 0.0
        
        # Risk trend
        portfolio_values = [p['value'] for p in self.portfolio_history if p['timestamp'] >= cutoff_time]
        risk_trend = "INCREASING" if len(portfolio_values) > 10 and \
                   portfolio_values[-1] < portfolio_values[-10] else "STABLE"
        
        return {
            "total_positions": len(self.position_risks),
            "average_risk_score": avg_risk,
            "max_drawdown": self.max_drawdown,
            "recent_alerts": len(recent_alerts),
            "critical_alerts": len([a for a in recent_alerts if a.severity == "CRITICAL"]),
            "current_risk_level": self._classify_risk_level(avg_risk),
            "risk_trend": risk_trend,
            "highest_risk_positions": sorted(
                [(symbol, risk.total_risk) for symbol, risk in self.position_risks.items()],
                key=lambda x: x[1], reverse=True
            )[:5],
            "correlation_exposure": self._calculate_correlation_exposure()
        }
    
    def _calculate_diversification_factor(self, positions: Dict[str, float]) -> float:
        """Calculate portfolio diversification factor"""
        if not positions:
            return 0.0
        
        # Shannon diversity index for symbols
        total_value = sum(positions.values())
        if total_value == 0:
            return 0.0
        
        probabilities = [value / total_value for value in positions.values()]
        h = -sum(p * math.log(p) for p in probabilities if p > 0)
        max_h = math.log(len(positions))
        
        return h / max_h if max_h > 0 else 0.0
    
    def _calculate_position_correlation_risk(self, symbol: str) -> float:
        """Calculate correlation risk for specific position"""
        correlations = []
        for other_symbol, risk in self.position_risks.items():
            if other_symbol != symbol:
                correlation = self.correlation_matrix.get(symbol, {}).get(other_symbol, 0.0)
                position_weight = risk.position_size / 1000000  # Normalize
                weighted_correlation = abs(correlation) * position_weight
                correlations.append(weighted_correlation)
        
        return statistics.mean(correlations) if correlations else 0.0
    
    def _calculate_market_volatility_level(self) -> float:
        """Calculate overall market volatility level"""
        if not self.volatility_data:
            return 0.0
        
        market_volatilities = []
        for symbol, vol_data in self.volatility_data.items():
            if vol_data:
                recent_vol = statistics.mean(list(vol_data)[-5:]) if len(vol_data) > 5 else 0.0
                market_volatilities.append(recent_vol)
        
        return statistics.mean(market_volatilities) if market_volatilities else 0.0
    
    def _detect_correlation_spike(self) -> bool:
        """Detect if there are correlation spikes in the market"""
        if not self.correlation_matrix:
            return False
        
        high_correlations = []
        for symbol1, correlations in self.correlation_matrix.items():
            for symbol2, correlation in correlations.items():
                if symbol1 != symbol2 and abs(correlation) > 0.8:
                    high_correlations.append(correlation)
        
        return len(high_correlations) > 3  # More than 3 high correlations
    
    def _assess_liquidity_conditions(self) -> str:
        """Assess overall liquidity conditions"""
        if not self.liquidity_scores:
            return "MODERATE"
        
        avg_liquidity = statistics.mean(self.liquidity_scores.values())
        
        if avg_liquidity > 0.8:
            return "GOOD"
        elif avg_liquidity > 0.5:
            return "MODERATE"
        else:
            return "POOR"
    
    def _assess_whale_activity_risk(self) -> str:
        """Assess risk from whale activity level"""
        # This would integrate with whale activity monitoring
        # For now, return moderate risk
        return "MEDIUM"
    
    def _identify_market_risk_factors(self, volatility: float, correlation_spike: bool, 
                                    liquidity: str) -> List[str]:
        """Identify specific market risk factors"""
        factors = []
        
        if volatility > 0.05:
            factors.append("HIGH_VOLATILITY")
        
        if correlation_spike:
            factors.append("CORRELATION_SPIKE")
        
        if liquidity == "POOR":
            factors.append("POOR_LIQUIDITY")
        elif liquidity == "MODERATE":
            factors.append("MODERATE_LIQUIDITY")
        
        return factors
    
    def _calculate_market_stress_score(self, volatility: float, correlation_spike: bool,
                                     liquidity: str, whale_activity: str) -> float:
        """Calculate overall market stress score"""
        stress_components = []
        
        # Volatility stress
        stress_components.append(min(1.0, volatility * 20))
        
        # Correlation stress
        stress_components.append(1.0 if correlation_spike else 0.0)
        
        # Liquidity stress
        liquidity_stress = {"GOOD": 0.0, "MODERATE": 0.3, "POOR": 0.7}[liquidity]
        stress_components.append(liquidity_stress)
        
        # Whale activity stress
        whale_stress = {"LOW": 0.0, "MEDIUM": 0.2, "HIGH": 0.5, "EXTREME": 0.8}[whale_activity]
        stress_components.append(whale_stress)
        
        return statistics.mean(stress_components)
    
    def _determine_market_regime(self, stress_score: float) -> str:
        """Determine current market regime"""
        if stress_score > 0.8:
            return "CRISIS"
        elif stress_score > 0.6:
            return "HIGH_STRESS"
        elif stress_score > 0.4:
            return "MODERATE_STRESS"
        else:
            return "NORMAL"
    
    def _calculate_recommended_aggression(self, stress_score: float) -> float:
        """Calculate recommended trading aggression based on market stress"""
        return max(0.1, 1.0 - stress_score)
    
    def reset_risk_data(self):
        """Reset all risk tracking data"""
        self.portfolio_history.clear()
        self.position_risks.clear()
        self.risk_alerts.clear()
        self.max_drawdown = 0.0
        self.peak_portfolio_value = 0.0
        self.volatility_data.clear()
        self.correlation_matrix.clear()
        self.liquidity_scores.clear()
        
        logger.info("Risk management data reset")