async def initialize_trading_system():
    try:
        # Initialize TradingCore with consistent configuration
        private_key = os.getenv('SOLANA_PRIVATE_KEY')
        key_bytes = base58.b58decode(private_key)
        
        trading_core = TradingCore(key_bytes)
        trade_config = TradeConfig()
        trade_config.compute_limit = 800000
        trade_config.priority_fee = 900000
        trade_config.skip_preflight = True
        trade_config.max_retries = 4
        trade_config.commitment = "confirmed"
        
        trading_core.update_config(trade_config)
        
        # Initialize CLI with existing trading core
        solana_cli = SolanaCLI(trading_core)
        await solana_cli.start()
        
        return trading_core, solana_cli
        
    except Exception as e:
        logger.error(f"Failed to initialize trading system: {str(e)}")
        raise

# Update your main() function to use this:
async def main():
    try:
        trading_core, solana_cli = await initialize_trading_system()
        
        # Use these instances for other components
        # Example:
        async with solana_cli:
            while True:
                await asyncio.sleep(1)
                
    except KeyboardInterrupt:
        logger.info("Shutting down...")
    except Exception as e:
        logger.error(f"Critical error: {str(e)}")
    finally:
        if 'solana_cli' in locals():
            await solana_cli.cleanup()

if __name__ == "__main__":
    try:
        if sys.platform == 'win32':
            asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
        asyncio.run(main())
    except KeyboardInterrupt:
        pass
    except Exception as e:
        logger.error(f"Fatal error: {str(e)}")
        sys.exit(1)         i need that stuff in here actually and can u write the full script fo rme all of it import asyncio
import os
import sys
from pathlib import Path
import torch
from dotenv import load_dotenv
import base58
from typing import Optional, List
import contextlib
from concurrent.futures import ThreadPoolExecutor
import aiohttp
import socket
from contextlib import AsyncExitStack, asynccontextmanager
import logging
import time
import psutil
import signal

# Import core components
from system_manager import SystemManager
from helius_client import HeliusWbSocketClient
from price_monitor import RaydiumMonitor
from mempool_analyzer import EnhancedMempoolAnalyzer
from solana_rust_bot import TradingCore, TradeConfig
from gpu_accelerator import GPUAccelerator, AcceleratorConfig
from vector_store import EnhancedVectorStore
from raydium_parser import RaydiumParser
from price_impact import PriceImpactCalculator
from solana_cli import SolanaCLI
from config_loader import config
from trade_executor import TradeExecutor
from optimized_parser import EnhancedParser
from advanced_trading import AdvancedMEVTrading
from solana_logger import SolanaLogger, log_info, log_error, log_debug

# Initialize logger
logger = SolanaLogger(__name__)

# Set Windows event loop policy
if sys.platform == 'win32':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

@asynccontextmanager
async def managed_client_session(**kwargs):
    """Context manager for aiohttp ClientSession"""
    async with aiohttp.ClientSession(**kwargs) as session:
        yield session

class TradingSystem:
    def __init__(self):
        """Initialize trading system with enhanced monitoring"""
        try:
            logger.info("Starting trading system initialization")
            self.initialized = False
            self.is_shutting_down = False
            self.exit_stack = AsyncExitStack()
            self.sessions = []
            self.cleanup_tasks = []
            self.system_tasks = set()
            self.ws_client = None  # Initialize after trading core setup
            # Initialize thread pool
            self.thread_pool = ThreadPoolExecutor(max_workers=4)
            
            # Initialize monitors
            self.initialized_components = set()
            self.component_health = {}
            self.last_health_check = 0
            
            # Initialize performance metrics
            self.metrics = {
                'initialization_time': 0,
                'uptime': 0,
                'component_stats': {},
                'error_counts': {},
                'memory_usage': {}
            }

            # Initialize component placeholders
            self._init_component_placeholders()

            logger.info("Trading system base initialization complete")
        except Exception as e:
            logger.error(f"Trading system initialization failed: {str(e)}")
            raise

    def _init_component_placeholders(self):
        """Initialize component placeholders"""
        self.system_manager = None
        self.trading_core = None
        self.gpu_accelerator = None
        self.vector_store = None
        self.price_monitor = None
        self.mempool_analyzer = None
        self.solana_cli = None
        self.trade_executor = None
        self.impact_calculator = None
        self.advanced_mev_trading = None

    async def __aenter__(self):
        """Async context manager entry with error handling"""
        await self.initialize()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        """Async context manager exit with graceful shutdown"""
        await self.shutdown()

    async def create_session(self, **kwargs) -> aiohttp.ClientSession:
        """Create and track a new client session"""
        async with managed_client_session(**kwargs) as session:
            self.sessions.append(session)
            return session

    async def initialize(self):
        """Comprehensive system initialization with dependency tracking"""
        try:
            init_start = time.time()
            logger.info("Starting trading system initialization")

            # Load environment variables
            if not await self._load_environment():
                raise ValueError("Failed to load environment configuration")

            # Initialize components sequentially with dependency tracking
            await self._setup_device()
            await self._initialize_trading_core()
            await self._initialize_gpu_accelerator()
            await self._initialize_core_components()
            await self._initialize_advanced_components()

            self.initialization_time = time.time() - init_start
            self.metrics['initialization_time'] = self.initialization_time
            self.initialized = True

            logger.info("Trading system initialization completed", extra={
                'initialization_time': f"{self.initialization_time:.2f}s",
                'initialized_components': list(self.initialized_components)
            })

        except Exception as e:
            logger.error(f"System initialization failed: {str(e)}")
            await self.shutdown()
            raise

    async def _load_environment(self) -> bool:
        """Load and validate environment configuration"""
        try:
            logger.debug("Loading environment variables")
            load_dotenv(override=True)

            # Validate required variables
            required_vars = {
                'SOLANA_PRIVATE_KEY': os.getenv('SOLANA_PRIVATE_KEY'),
                'HELIUS_WS_URL': os.getenv('HELIUS_WS_URL'),
                'RAYDIUM_PROGRAM_ID': os.getenv('RAYDIUM_PROGRAM_ID'),
                'WSOL_TOKEN_ACCOUNT': os.getenv('WSOL_TOKEN_ACCOUNT'),
                'RPC_URL': os.getenv('RPC_URL'),
                'HELIUS_API_KEY': os.getenv('HELIUS_API_KEY')
            }

            missing = [k for k, v in required_vars.items() if not v]
            if missing:
                logger.error("Missing required environment variables", extra={
                    'missing_vars': missing
                })
                return False

            return True

        except Exception as e:
            logger.error(f"Environment loading error: {str(e)}")
            return False

    async def _setup_device(self):
        """Setup compute device with optimizations"""
        try:
            logger.debug("Setting up compute device")
            if torch.cuda.is_available():
                self.device = torch.device("cuda")
                torch.backends.cudnn.benchmark = True
                torch.backends.cuda.matmul.allow_tf32 = True
                torch.cuda.set_device(0)

                device_props = torch.cuda.get_device_properties(0)
                logger.info("GPU initialized successfully", extra={
                    'device': torch.cuda.get_device_name(),
                    'memory': device_props.total_memory,
                    'compute_capability': device_props.major
                })
            else:
                self.device = torch.device("cpu")
                logger.warning("No GPU available, using CPU")

        except Exception as e:
            logger.error(f"Device setup failed: {str(e)}")
            raise

    async def _initialize_trading_core(self):
        """Initialize trading core with enhanced validation"""
        try:
            logger.debug("Initializing trading core")
        
            # Get and decode private key
            private_key_str = os.environ.get('SOLANA_PRIVATE_KEY')
            if not private_key_str:
                raise ValueError("SOLANA_PRIVATE_KEY not found in environment")
        
            key_bytes = base58.b58decode(private_key_str)
        
            # Initialize trading core with optimized configuration
            self.trading_core = TradingCore(key_bytes)
        
            # Configure trading parameters
            trade_config = TradeConfig()
            trade_config.compute_limit = int(os.getenv('COMPUTE_LIMIT', '400000'))
            trade_config.priority_fee = int(os.getenv('PRIORITY_FEE', '500000'))
            trade_config.max_retries = int(os.getenv('MAX_RETRIES', '3'))
        
            # Call update_config directly (not awaited)
            self.trading_core.update_config(trade_config)
        
            self.initialized_components.add('trading_core')
        
            logger.info("Trading core initialized successfully")

        except Exception as e:
            logger.error(f"Trading core initialization failed: {str(e)}")
            raise

    async def _initialize_gpu_accelerator(self):
        """Initialize GPU Accelerator with proper async handling"""
        try:
            logger.debug("Initializing GPU Accelerator")
            
            # Create accelerator config
            accelerator_config = AcceleratorConfig(
                memory_fraction=float(os.getenv('GPU_MEMORY_FRACTION', '0.8')),
                batch_size=int(os.getenv('GPU_BATCH_SIZE', '32')),
                use_amp=os.getenv('USE_AMP', 'true').lower() == 'true',
                use_tensor_cores=os.getenv('GPU_USE_TENSOR_CORES', 'true').lower() == 'true'
            )
            
            # Initialize accelerator
            self.gpu_accelerator = GPUAccelerator(accelerator_config)
            
            # Add to exit stack for proper cleanup
            await self.exit_stack.enter_async_context(self.gpu_accelerator)
            self.initialized_components.add('gpu_accelerator')
            
            logger.info("GPU Accelerator initialized successfully")

        except Exception as e:
            logger.error(f"GPU Accelerator initialization failed: {str(e)}")
            raise

    async def _initialize_core_components(self):
        """Initialize core system components with dependency tracking"""
        try:
            logger.debug("Initializing core components")
            
            # Initialize system manager
            self.system_manager = SystemManager()
            await self.system_manager.start()
            await self.exit_stack.enter_async_context(self.system_manager)
            
            # Initialize vector store
            self.vector_store = EnhancedVectorStore()
            await self.exit_stack.enter_async_context(self.vector_store)
            
            # Initialize Solana CLI
            self.solana_cli = SolanaCLI(self.trading_core)
            await self.exit_stack.enter_async_context(self.solana_cli)
            
            # Initialize trade executor
            self.trade_executor = TradeExecutor(self.trading_core)
            await self.exit_stack.enter_async_context(self.trade_executor)
            
            # Initialize other core components
            self.impact_calculator = PriceImpactCalculator()
            self.raydium_parser = RaydiumParser()
            self.optimized_parser = EnhancedParser()

            # Update initialized components
            self.initialized_components.update({
                'system_manager',
                'vector_store',
                'solana_cli',
                'trade_executor',
                'impact_calculator'
            })
            
            logger.info("Core components initialized successfully")

        except Exception as e:
            logger.error(f"Core components initialization failed: {str(e)}")
            raise

    async def _initialize_advanced_components(self):
        """Initialize advanced trading components with optimized networking"""
        try:
            logger.debug("Initializing advanced components")
            
            # Create optimized network session
            connector = aiohttp.TCPConnector(
                family=socket.AF_INET,
                ssl=False,
                force_close=True,
                enable_cleanup_closed=True
            )
            session = await self.create_session(connector=connector)
            
            # Initialize components with proper dependency injection
            self.mempool_analyzer = EnhancedMempoolAnalyzer(self.trading_core)
            await self.exit_stack.enter_async_context(self.mempool_analyzer)
            
            self.advanced_mev_trading = AdvancedMEVTrading(
                trading_core=self.trading_core,
                session=session
            )
            await self.exit_stack.enter_async_context(self.advanced_mev_trading)
            
            self.price_monitor = RaydiumMonitor()
            await self.exit_stack.enter_async_context(self.price_monitor)
            
            # Initialize the Helius WebSocket client
            self.ws_client = HeliusWbSocketClient(
                trading_core=self.trading_core,
                mempool_analyzer=self.mempool_analyzer
            )
            await self.exit_stack.enter_async_context(self.ws_client)

            # Update initialized components
            self.initialized_components.update({
                'mempool_analyzer',
                'advanced_mev_trading',
                'price_monitor',
                'ws_client'
            })
            
            logger.info("Advanced components initialized successfully")

        except Exception as e:
            logger.error(f"Advanced components initialization failed: {str(e)}")
            raise

    async def start(self):
        """Start all system components with health monitoring"""
        if not self.initialized:
            await self.initialize()

        try:
            logger.info("Starting system components")
            
            # Start core services
            await self.solana_cli.start()
            await self.price_monitor.start_monitoring()
            await self.ws_client.start()
            await self.advanced_mev_trading.start()
            await self.vector_store.start()
            
            # Start monitoring
            monitor_task = asyncio.create_task(
                self._monitor_system_health(),
                name="health_monitor"
            )
            self.system_tasks.add(monitor_task)
            
            logger.info("All components started successfully")

        except Exception as e:
            logger.error(f"System startup failed: {str(e)}")
            await self.shutdown()
            raise

    async def _monitor_system_health(self):
        """Monitor system health with comprehensive metrics"""
        while not self.is_shutting_down:
            try:
                # Check component health
                for component in self.initialized_components:
                    if hasattr(self, component):
                        component_obj = getattr(self, component)
                        if hasattr(component_obj, 'get_health'):
                            health = await component_obj.get_health()
                            self.component_health[component] = health

                # Update system metrics
                self.metrics.update({
                    'uptime': time.time() - self.metrics['initialization_time'],
                    'component_stats': self.component_health,
                    'memory_usage': {
                        'system': psutil.Process().memory_info().rss / 1024**2,
                        'gpu': torch.cuda.memory_allocated() / 1024**2 
                        if torch.cuda.is_available() else 0
                    }
                })

                # Log metrics periodically
                if int(time.time()) % 300 == 0:  # Every 5 minutes
                    logger.info("System health metrics", extra={
                        'metrics': self.metrics
                    })

                await asyncio.sleep(1)

            except Exception as e:
                logger.error(f"Health monitoring error: {str(e)}")
                await asyncio.sleep(5)

    async def shutdown(self):
        """Comprehensive system shutdown and cleanup"""
        if self.is_shutting_down:
            return

        self.is_shutting_down = True
        logger.info("Initiating system shutdown")

        try:
            # Cancel system tasks
            for task in self.system_tasks:
                task.cancel()
                try:
                    await task
                except asyncio.CancelledError:
                    pass

            # Close exit stack (handles component cleanup)
            await self.exit_stack.aclose()

            # Shutdown thread pool
            self.thread_pool.shutdown(wait=True)

            # Log final metrics
            logger.info("System shutdown complete", extra={
                'final_metrics': self.metrics,
                'uptime': time.time() - self.metrics['initialization_time'],
                'initialized_components': list(self.initialized_components)
            })

            # Clear component references
            self._clear_components()

        except Exception as e:
            logger.error(f"Error during shutdown: {str(e)}")
        finally:
            self.initialized = False
            self.is_shutting_down = False

    def _clear_components(self):
        """Clear all component references"""
        self.system_manager = None
        self.trading_core = None
        self.gpu_accelerator = None
        self.vector_store = None
        self.price_monitor = None
        self.ws_client = None
        self.advanced_mev_trading = None
        self.mempool_analyzer = None
        self.solana_cli = None
        self.trade_executor = None
        self.impact_calculator = None

async def main():
    """Main entry point with comprehensive error handling"""
    trading_system = None
    
    try:
        # Setup initial logging
        log_dir = Path("logs")
        log_dir.mkdir(exist_ok=True)
        
        log_info("Starting Solana trading system")

        # System information
        log_debug(f"Python version: {sys.version}")
        log_debug(f"Current directory: {os.getcwd()}")
        log_debug(f"PYTHONPATH: {os.environ.get('PYTHONPATH', 'Not set')}")

        # Initialize trading system
        log_info("Initializing trading system...")
        trading_system = TradingSystem()
        
        async with trading_system:
            log_info("Trading system initialized, starting components...")
            await trading_system.start()
            
            # Create event to handle shutdown
            shutdown_event = asyncio.Event()
            
            def signal_handler():
                log_info("Shutdown signal received")
                shutdown_event.set()
            
            # Register signal handlers
            for sig in (signal.SIGTERM, signal.SIGINT):
                loop = asyncio.get_running_loop()
                loop.add_signal_handler(sig, signal_handler)
            
            log_info("Trading system running, waiting for signals...")
            # Wait for shutdown signal
            await shutdown_event.wait()

    except KeyboardInterrupt:
        log_info("Graceful shutdown initiated")
    except Exception as e:
        log_error(f"Critical system error: {str(e)}")
    finally:
        if trading_system and trading_system.initialized:
            log_info("Shutting down trading system...")
            try:
                await trading_system.shutdown()
                log_info("Shutdown complete")
            except Exception as e:
                log_error(f"Error during final cleanup: {str(e)}")

if __name__ == "__main__":
    try:
        # Configure event loop for Windows
        if sys.platform == 'win32':
            asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
        
        # Create event loop
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        
        # Set debug if configured
        if os.getenv('DEBUG', 'false').lower() == 'true':
            loop.set_debug(True)
            logging.getLogger('asyncio').setLevel(logging.DEBUG)
        
        # Run main
        try:
            loop.run_until_complete(main())
        except KeyboardInterrupt:
            pass
        finally:
            try:
                # Clean up pending tasks
                pending = asyncio.all_tasks(loop)
                if pending:
                    loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
            finally:
                loop.close()
                
    except Exception as e:
        log_error(f"Failed to start trading system: {str(e)}")
        sys.exit(1)