please add maximum logging # main.py

import asyncio
import logging
from pathlib import Path
import time
from config import Config
from config_validator import ConfigValidator
from quantum_optimized import QuantumOptimized
from monitor import MonitorServer
from dashboard_server import DashboardServer
import os
import sys
import json
from typing import Optional, Dict, Tuple

def setup_logging() -> None:
    """Configure logging with timestamp and both file/console output"""
    log_format = '%(asctime)s | %(levelname)s | %(message)s'
    
    # Create logs directory
    Path("logs").mkdir(exist_ok=True)
    timestamp = time.strftime('%Y%m%d_%H%M%S')
    
    # Configure handlers
    file_handler = logging.FileHandler(
        f"logs/quantum_{timestamp}.log",
        encoding='utf-8'
    )
    console_handler = logging.StreamHandler()
    
    # Set formatting
    formatter = logging.Formatter(log_format)
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)
    
    # Configure root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    root_logger.addHandler(file_handler)
    root_logger.addHandler(console_handler)
    
    # Suppress noisy logs
    logging.getLogger("websockets").setLevel(logging.WARNING)
    logging.getLogger("asyncio").setLevel(logging.WARNING)

def verify_system() -> None:
    """Verify system requirements and GPU availability"""
    import torch
    logger = logging.getLogger(__name__)
    
    if not torch.cuda.is_available():
        raise RuntimeError("CUDA not available. GPU required for trading.")
    
    device_props = torch.cuda.get_device_properties(0)
    logger.info(f"GPU: {device_props.name}")
    logger.info(f"CUDA Version: {torch.version.cuda}")
    logger.info(f"PyTorch Version: {torch.__version__}")
    logger.info(f"GPU Memory: {device_props.total_memory / 1024**3:.1f}GB")
    
    if device_props.total_memory < 8 * 1024**3:  # 8GB
        logger.warning(f"Low GPU memory: {device_props.total_memory / 1024**3:.1f}GB. 8GB+ recommended.")

def verify_config() -> str:
    """Verify configuration files and paths"""
    logger = logging.getLogger(__name__)
    config_path = str(Path(__file__).parent.parent.parent / "config.json")
    
    if not Path(config_path).exists():
        raise FileNotFoundError(f"Config file not found at {config_path}")
    
    try:
        # Load and parse config
        with open(config_path, 'r') as f:
            config_data = json.load(f)
        
        # Verify TPS configuration
        trading_config = config_data.get('trading', {})
        required_tps_fields = {
            'trades_per_second',
            'max_trades_per_second',
            'tps_increment',
            'tps_increment_interval'
        }
        
        # Check for missing fields
        missing_fields = required_tps_fields - set(trading_config.keys())
        if missing_fields:
            logger.error(f"Missing TPS config fields: {missing_fields}")
            raise ValueError("Missing required TPS configuration fields")
            
        # Validate TPS values
        if not 0 < trading_config['trades_per_second'] <= trading_config['max_trades_per_second']:
            raise ValueError("Invalid trades_per_second range")
            
        if trading_config['tps_increment'] <= 0:
            raise ValueError("TPS increment must be positive")
            
        if trading_config['tps_increment_interval'] <= 0:
            raise ValueError("TPS increment interval must be positive")
        
        # Load full config for additional validation
        config = Config.load(config_path)
        
        # Validate core configuration
        if not config.validate():
            raise ValueError("Failed to validate core configuration")
            
        # Validate keypair path
        keypair_path = Path(config.wallet.get('keypair_path', ''))
        if not keypair_path.exists():
            raise FileNotFoundError(f"Keypair file not found at {keypair_path}")
        
        # Validate RPC settings
        if not config.rpc.get('primary', {}).get('endpoint'):
            raise ValueError("Missing primary RPC endpoint")
            
        logger.info("Configuration validated successfully")
        return config_path
        
    except Exception as e:
        logger.error(f"Config verification error: {str(e)}")
        raise

async def initialize_components(config_path: str) -> Tuple[Config, QuantumOptimized, MonitorServer, DashboardServer]:
    """Initialize system components"""
    logger = logging.getLogger(__name__)
    
    try:
        # Load config
        config = Config.load(config_path)
        
        # Initialize quantum system
        quantum_system = QuantumOptimized(config)
        
        # Initialize monitoring
        monitor = MonitorServer(
            trading_core=quantum_system.market_data.core,
            market_data=quantum_system.market_data,
            ml_engine=quantum_system.ml_engine,
            groq_analyzer=quantum_system.groq_analyzer
        )
        
        # Initialize dashboard
        dashboard = DashboardServer(
            trading_core=quantum_system.market_data.core,
            market_data=quantum_system.market_data,
            ml_engine=quantum_system.ml_engine,
            groq_analyzer=quantum_system.groq_analyzer
        )
        
        return config, quantum_system, monitor, dashboard
        
    except Exception as e:
        logger.error(f"Failed to initialize components: {e}")
        raise

async def main() -> None:
    initial_balance = 0.0
    try:
        # Setup logging
        setup_logging()
        logger = logging.getLogger(__name__)
        logger.info("🚀 Starting Quantum Trading System")
        
        # System checks
        verify_system()
        config_path = verify_config()
        
        # Initialize components
        config, quantum_system, monitor, dashboard = await initialize_components(config_path)
        
        # Get initial balance
        initial_balance = await quantum_system.market_data.get_balance()
        logger.info(f"Initial balance: {initial_balance:.6f} SOL")
        
        if initial_balance < 0.025:
            raise ValueError(f"Insufficient balance: {initial_balance:.6f} SOL")
        
        # Log startup configuration
        logger.info("\n=== System Configuration ===")
        logger.info(f"Initial Balance: {initial_balance:.6f} SOL")
        logger.info(f"Position Size: {config.trading.get('position_size')} SOL")
        logger.info(f"Max Position: {config.trading.get('max_position')} SOL")
        logger.info(f"Batch Size: {config.system.get('batch_size')}")
        logger.info(f"GPU Threads: {config.system.get('gpu_threads')}")
        logger.info("Dashboard URL: ws://localhost:8766\n")
        
        # Start all services
        async with asyncio.TaskGroup() as tg:
            tg.create_task(monitor.start_server())
            tg.create_task(dashboard.start_server())
            tg.create_task(quantum_system.start())
            
            logger.info("All systems operational! Press Ctrl+C to stop.")
            
            while True:
                await asyncio.sleep(1)
        
    except* asyncio.CancelledError:
        logger.info("System shutdown initiated")
    except* Exception as e:
        logger.error(f"Fatal error: {e}", exc_info=True)
        raise
    finally:
        # Cleanup and final status
        logger.info("Cleaning up resources...")
        try:
            if 'quantum_system' in locals():
                await quantum_system.cleanup()
                final_balance = await quantum_system.market_data.get_balance()
                profit = ((final_balance - initial_balance) / initial_balance) * 100
                logger.info(f"Final balance: {final_balance:.6f} SOL")
                logger.info(f"Session profit: {profit:.2f}%")
        except Exception as e:
            logger.error(f"Cleanup error: {e}")

if __name__ == "__main__":
    try:
        if sys.platform.startswith('win'):
            asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nShutdown requested... closing system.")
    except Exception as e:
        print(f"Unexpected error: {e}")
        raise