add debugg logging all throughout this script please import logging
import time
import json
import numpy as np
from typing import Dict, Set, Optional, Tuple, List
from dataclasses import dataclass
import torch

@dataclass
class RiskMetrics:
    """Risk assessment metrics"""
    liquidity_score: float
    volume_score: float
    holder_score: float
    price_impact: float
    market_cap_score: float
    bs_ratio: float
    risk_level: float  # 0 = lowest risk, 1 = highest risk

class QuantumRisk:
    """Unified risk management and position scaling"""
    
    def __init__(self, config, trading_core):
        """Initialize risk management with config and Rust backend"""
        self.config = config
        self.trading_core = trading_core
        self.logger = logging.getLogger(__name__)
        
        # Initialize from config
        self._init_risk_params()
        
        # State tracking
        self.blacklisted_tokens: Set[str] = set()
        self.failed_validations: Dict[str, int] = {}
        self.position_sizes: Dict[str, float] = {}
        self.last_trade_time = 0
        self.trade_history: List[Dict] = []
        
        # Performance tracking
        self.validation_times = []
        self.position_adjustments = []

        # GPU setup if available
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        if torch.cuda.is_available():
            self.logger.info(f"Risk calculations using {torch.cuda.get_device_name(0)}")
    
    def _init_risk_params(self):
        """Initialize risk parameters from config"""
        # Trading thresholds
        trading_config = self.config["trading"]
        self.min_volume = trading_config.get("min_volume", 0.1)
        self.min_liquidity = trading_config.get("min_liquidity", 1.0)
        self.min_bs_ratio = trading_config.get("min_bs_ratio", 1.1)
        self.max_price_impact = trading_config.get("max_price_impact", 0.01)
        
        # Position sizing
        self.base_size = trading_config.get("position_size", 0.02)
        self.max_size = trading_config.get("max_position", 0.15)
        self.position_step = trading_config.get("position_step_size", 0.02)
        
        # Safeguard thresholds
        safety_config = self.config["safety"]
        self.min_holders = safety_config.get("min_holders", 100)
        self.max_whale_pct = safety_config.get("max_whale_pct", 10.0)
        self.volume_spike_threshold = safety_config.get("volume_spike_threshold", 3.0)
        self.price_spike_threshold = safety_config.get("price_spike_threshold", 2.0)

    async def validate_trade(self, pool_data: Dict, ml_signal: Dict) -> Tuple[bool, str]:
        """Validate trade against all risk criteria"""
        try:
            start_time = time.time()
            token_mint = pool_data["token_mint"]
            
            # Check blacklist
            if token_mint in self.blacklisted_tokens:
                return False, "Token is blacklisted"

            # Get risk metrics
            risk_metrics = self._calculate_risk_metrics(pool_data)
            
            # Core validation checks
            validations = {
                "liquidity": risk_metrics.liquidity_score >= self.min_liquidity,
                "volume": risk_metrics.volume_score >= self.min_volume,
                "bs_ratio": risk_metrics.bs_ratio >= self.min_bs_ratio,
                "price_impact": risk_metrics.price_impact <= self.max_price_impact,
                "risk_level": risk_metrics.risk_level <= 0.8,  # Max 80% risk tolerance
                "ml_confidence": ml_signal.get("confidence", 0) >= self.config["ml_signal"]["confidence_score"]
            }

            # Check all validations
            is_valid = all(validations.values())
            
            # Update tracking
            self.validation_times.append(time.time() - start_time)
            if not is_valid:
                self._record_failed_validation(token_mint)
            
            # Get validation message
            message = "Trade validated" if is_valid else f"Validation failed: {[k for k, v in validations.items() if not v]}"
            
            return is_valid, message

        except Exception as e:
            self.logger.error(f"Trade validation error: {e}")
            return False, f"Validation error: {str(e)}"

    def _calculate_risk_metrics(self, pool_data: Dict) -> RiskMetrics:
        """Calculate comprehensive risk metrics"""
        try:
            # Calculate core metrics
            volume = float(pool_data.get("volume_5min", 0))
            liquidity = float(pool_data.get("liquidity", 1))
            market_cap = float(pool_data.get("market_cap", 0))
            buy_pressure = float(pool_data.get("buy_pressure", 0))
            sell_pressure = max(float(pool_data.get("sell_pressure", 1)), 1)

            # Calculate scores (0-1 scale)
            liquidity_score = min(liquidity / 100000, 1.0)
            volume_score = min(volume / 10000, 1.0)
            market_cap_score = min(market_cap / 1000000, 1.0)
            bs_ratio = buy_pressure / sell_pressure
            
            # Calculate price impact using Rust backend
            impact_data = {
                "token_mint": pool_data["token_mint"],
                "amount": self.base_size * 1e9  # Convert to lamports
            }
            price_impact = float(self.trading_core.calculate_price_impact(json.dumps(impact_data)))
            
            # Calculate overall risk level
            risk_components = [
                1 - liquidity_score,
                1 - volume_score,
                1 - market_cap_score,
                price_impact / self.max_price_impact,
                0.5 if bs_ratio < 1 else 0
            ]
            risk_level = sum(risk_components) / len(risk_components)

            return RiskMetrics(
                liquidity_score=liquidity_score,
                volume_score=volume_score,
                holder_score=1.0,  # Default until holder data available
                price_impact=price_impact,
                market_cap_score=market_cap_score,
                bs_ratio=bs_ratio,
                risk_level=risk_level
            )

        except Exception as e:
            self.logger.error(f"Risk metrics calculation error: {e}")
            return self._get_default_risk_metrics()

    async def get_position_size(self, pool_data: Dict, ml_signal: Dict) -> float:
        """Calculate optimal position size"""
        try:
            # Get current wallet balance from Rust backend
            balance = self.trading_core.get_balance()
            if balance < self.base_size:
                return 0.0

            # Calculate base size adjustments
            confidence_mul = ml_signal.get("confidence", 0)
            risk_metrics = self._calculate_risk_metrics(pool_data)
            
            # Adjust size based on risk and ML confidence
            size_adjustments = {
                "risk": 1 - risk_metrics.risk_level,  # Lower risk = higher size
                "confidence": confidence_mul,
                "liquidity": risk_metrics.liquidity_score,
                "market": self._get_market_multiplier(pool_data)
            }
            
            # Calculate final size
            adjusted_size = self.base_size
            for factor, value in size_adjustments.items():
                adjusted_size *= value
            
            # Apply limits
            final_size = min(max(adjusted_size, self.base_size), self.max_size)
            final_size = min(final_size, balance * 0.9)  # Never use more than 90% of balance
            
            # Update tracking
            self.position_sizes[pool_data["token_mint"]] = final_size
            self.position_adjustments.append(final_size / self.base_size)
            
            return final_size

        except Exception as e:
            self.logger.error(f"Position size calculation error: {e}")
            return self.base_size

    def _get_market_multiplier(self, pool_data: Dict) -> float:
        """Calculate market condition multiplier"""
        try:
            buy_pressure = float(pool_data.get("buy_pressure", 0))
            sell_pressure = max(float(pool_data.get("sell_pressure", 1)), 1)
            
            # Calculate market sentiment
            bs_ratio = buy_pressure / sell_pressure
            if bs_ratio > 1.5:
                return 1.2  # Strong buy pressure
            elif bs_ratio < 0.7:
                return 0.8  # Strong sell pressure
            return 1.0  # Neutral market
            
        except Exception as e:
            self.logger.error(f"Market multiplier error: {e}")
            return 1.0

    def _record_failed_validation(self, token_mint: str):
        """Record failed validation attempt"""
        if token_mint not in self.failed_validations:
            self.failed_validations[token_mint] = 0
        
        self.failed_validations[token_mint] += 1
        
        # Blacklist after multiple failures
        if self.failed_validations[token_mint] >= 3:
            self.blacklisted_tokens.add(token_mint)
            self.logger.warning(f"Token blacklisted after multiple validation failures: {token_mint}")

    def _get_default_risk_metrics(self) -> RiskMetrics:
        """Return default risk metrics"""
        return RiskMetrics(
            liquidity_score=0.0,
            volume_score=0.0,
            holder_score=0.0,
            price_impact=1.0,
            market_cap_score=0.0,
            bs_ratio=0.0,
            risk_level=1.0
        )

    async def check_exit_conditions(self, trade: Dict) -> bool:
        """Check if position should be exited"""
        try:
            # Get current price from Rust backend
            pool_info = json.loads(self.trading_core.get_pool_info(trade["token_mint"]))
            current_price = float(pool_info["price"])
            
            # Calculate profit/loss
            entry_price = float(trade["entry_price"])
            profit_pct = ((current_price - entry_price) / entry_price) * 100
            
            # Exit conditions
            conditions = {
                "take_profit": profit_pct >= 5.0,  # 5% profit target
                "stop_loss": profit_pct <= -2.0,   # 2% stop loss
                "time_limit": time.time() - float(trade["entry_time"]) > 3600,  # 1 hour max hold
                "risk_increase": self._calculate_risk_metrics(pool_info).risk_level > 0.9
            }
            
            should_exit = any(conditions.values())
            if should_exit:
                reason = [k for k, v in conditions.items() if v][0]
                self.logger.info(f"Exit signal for {trade['token_mint']}: {reason}")
                
            return should_exit

        except Exception as e:
            self.logger.error(f"Exit condition check error: {e}")
            return True  # Exit on error

    def record_trade_result(self, trade_data: Dict):
        """Record trade result for analysis"""
        try:
            self.trade_history.append(trade_data)
            if len(self.trade_history) > 1000:
                self.trade_history = self.trade_history[-1000:]
                
            # Update success metrics
            if trade_data.get("profit", 0) > 0:
                token_mint = trade_data["token_mint"]
                # Remove from blacklist if profitable
                self.blacklisted_tokens.discard(token_mint)
                self.failed_validations.pop(token_mint, None)
                
        except Exception as e:
            self.logger.error(f"Trade recording error: {e}")

    def get_metrics(self) -> Dict:
        """Get risk management metrics"""
        return {
            "blacklisted_tokens": len(self.blacklisted_tokens),
            "avg_validation_time": np.mean(self.validation_times) if self.validation_times else 0,
            "avg_position_adjustment": np.mean(self.position_adjustments) if self.position_adjustments else 1.0,
            "total_trades": len(self.trade_history),
            "active_positions": len(self.position_sizes)
        }

    async def cleanup(self):
        """Cleanup risk management resources"""
        try:
            self.logger.info("Cleaning up risk management...")
            self.blacklisted_tokens.clear()
            self.failed_validations.clear()
            self.position_sizes.clear()
            self.trade_history.clear()
            
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
                
            self.logger.info("Risk management cleanup complete")
            
        except Exception as e:
            self.logger.error(f"Cleanup error: {e}")
            raise  dont remove or weaken or lessen my code i want it the same way im giving it to you just add the debug logging