fix the spacing """
launcher.py - Quantum Trading System Launcher
Last Updated: December 2, 2024
"""

import asyncio
import logging
from typing import Dict, Optional, Any
from quantum_websocket import QuantumWebSocket
from market_signals import MarketSignals
from gui import QuantumGUI
from PyQt6.QtWidgets import QApplication
import sys

class QuantumLauncher:
   def __init__(self, config: Dict[str, Any]):
       """Initialize with provided config"""
       self.config = config
       self.logger = logging.getLogger(__name__)
       self.ws = None
       self.market_signals = None
       self.gui: Optional[QuantumGUI] = None
       
       # Handle wallet config
       try:
           self.wallet_config = {
               "address": config["wallet"]["address"],
               "keypair_path": config["wallet"]["keypair_path"]
           }
       except (KeyError, TypeError):
           self.wallet_config = {
               "address": "Not Connected",
               "keypair_path": ""
           }
           self.logger.warning("Wallet config not found or incomplete")
       
       # Set key configs with proper paths and defaults
       self.raydium_config = {
           "program_id": config["raydium"]["program_id"],
           "token_program": config["raydium"]["token_program"],
           "pool_program": config["raydium"]["pool_program"],
           "pool_authority": config["raydium"].get("pool_authority", "5Q544fKrFoe6tsEbD7S8EmxGTJYAKtTVhAW5Q5pge4j1"),
           "market_maker": config["raydium"].get("market_maker", "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"),
           "serum_program": config["raydium"].get("serum_program", "srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX")
       }
       
       self.jupiter_config = {
           "program_id": config["jupiter"]["program_id"],
           "quote_api": config["jupiter"]["quote_api"],
           "token_program": config["jupiter"]["token_program"],
           "index_program": config["jupiter"].get("index_program"),
           "strict_price": config["jupiter"].get("strict_price", True),
           "max_slippage": config["jupiter"].get("max_slippage", 0.5),
           "version": config["jupiter"].get("version", 6),
           "compute_price": config["jupiter"].get("compute_price", 400000)
       }
       
       self.helius_config = {
           "ws_endpoint": config["helius"]["ws_endpoint"],
           "rpc_endpoint": config["helius"]["rpc_endpoint"],
           "api_key": config["helius"]["api_key"]
       }
       
       self.trading_config = config["trading"]
       self.neural_config = config["neural"]
       self.risk_config = config["risk"]
       self.indicators_config = config["indicators"]
       
       self.running = False
       self.logger.info("Quantum Trading System Initialized")

   async def initialize(self):
       """Initialize system components"""
       try:
           # Initialize WebSocket with all required configs
           self.ws = QuantumWebSocket({
               "helius": self.helius_config,
               "jupiter": self.jupiter_config,
               "raydium": self.raydium_config,
               "trading": self.trading_config,
               "wallet": self.wallet_config
           })
           success = await self.ws.connect()
           if not success:
               raise Exception("Failed to connect WebSocket")
           
           # Initialize Market Signals with all required configs
           self.market_signals = MarketSignals({
               "trading": self.trading_config,
               "neural": self.neural_config,
               "indicators": self.indicators_config,
               "risk": self.risk_config
           })
           
           # Create QApplication instance if needed
           app = QApplication.instance()
           if app is None:
               app = QApplication(sys.argv)
           
           # Initialize GUI with all components and configs
           self.gui = QuantumGUI(
               config=self.config,
               trader=self.ws,
               market_signals=self.market_signals,
               scanner=self.market_signals
           )
           
           self.logger.info("System components initialized successfully")
           return True
           
       except Exception as e:
           self.logger.error(f"Initialization error: {e}")
           await self.cleanup()
           raise

   async def start(self):
       """Start all system services"""
       try:
           self.logger.info("Starting Quantum Trading System...")
           
           # Start market signals
           await self.market_signals.start()
           self.logger.info("Market signals processor started")
           
           # Start and show GUI
           self.gui.show()
           await self.gui.start()
           self.logger.info("GUI initialized and displayed")
           
           self.running = True
           self.logger.info("All services started successfully")
           
           # Start processing loop
           asyncio.create_task(self._processing_loop())
           
       except Exception as e:
           self.logger.error(f"Failed to start services: {e}")
           await self.cleanup()
           raise

   async def _processing_loop(self):
       """Main processing loop"""
       while self.running:
           try:
               # Get market data
               market_data = await self.ws.get_market_data()
               
               if market_data:
                   # Process market signals
                   signal = await self.market_signals.process_market_data(market_data)
                   
                   # Update GUI if signal generated
                   if signal:
                       self.gui.update_signal(signal)
                       
               await asyncio.sleep(0.001)  # 1ms loop time
               
           except Exception as e:
               self.logger.error(f"Processing error: {e}")
               await asyncio.sleep(1)

   async def cleanup(self):
       """Cleanup all resources"""
       self.logger.info("Cleaning up resources...")
       self.running = False
       
       try:
           if self.gui:
               await self.gui.cleanup()
           
           if self.ws:
               await self.ws.close()
           
           if self.market_signals:
               await self.market_signals.cleanup()
               
           self.logger.info("Cleanup completed successfully")
           
       except Exception as e:
           self.logger.error(f"Cleanup error: {e}")

    async def run_forever(self):
        """Run the system indefinitely"""
        try:
            # Initialize all components
            await self.initialize()
           
            # Start all services
            await self.start()
           
            # Keep the system running
            while self.running:
               await asyncio.sleep(0.1)
               
        except KeyboardInterrupt:
            self.logger.info("Shutdown requested by user...")
        except Exception as e:
            self.logger.error(f"Runtime error: {e}")
            raise
        finally:
            await self.cleanup()
           
    async def cleanup(self):
        """Cleanup all resources"""
        self.logger.info("Cleaning up resources...")
        self.running = False
       
        try:
            if self.gui:
                await self.gui.cleanup()
           
            if self.ws:
                await self.ws.close()
           
            if self.market_signals:
                await self.market_signals.cleanup()
               
            self.logger.info("Cleanup completed successfully")
           
        except Exception as e:
            self.logger.error(f"Cleanup error: {e}")