# main.py
import asyncio
import sys
import yaml
import logging
from PyQt6.QtWidgets import QApplication
from datetime import datetime
from pathlib import Path

# Local imports
from quantum_gui import QuantumGUI
from market_signals import MarketSignals 
from neural_engine import QuantumNeuralEngine
from quantum_trading import QuantumTrading
from atomic_executor import AtomicExecutor
from solana_rust_bot import QuantumTrader as RustTrader

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(f"quantum_{datetime.now().strftime('%Y%m%d')}.log"),
        logging.StreamHandler()
    ]
)

def load_config():
    try:
        with open("config.yml", "r") as f:
            config = yaml.safe_load(f)
            logging.info("Configuration loaded successfully")
            return config
    except Exception as e:
        logging.error(f"Failed to load config: {e}")
        raise

async def initialize_components(config):
    try:
        # Initialize core components
        trader = QuantumTrading(
            config['wallet']['keypair_path'],
            config['trading']['priority_fee']
        )
        logging.info("Trader initialized")

        market_signals = MarketSignals(config)
        logging.info("Market signals initialized")

        neural_engine = QuantumNeuralEngine()
        logging.info("Neural engine initialized")

        executor = AtomicExecutor(config)
        logging.info("Executor initialized")

        # Initialize GUI
        gui = QuantumGUI(
            config=config,
            trader=trader,
            market_signals=market_signals,
            neural_engine=neural_engine
        )
        logging.info("GUI initialized")

        # Initialize trading system
        quantum = QuantumTrading(gui, config)
        logging.info("Quantum trading initialized")

        return gui, market_signals, quantum, executor

    except Exception as e:
        logging.error(f"Component initialization failed: {str(e)}")
        raise

async def cleanup_components(components):
    gui, market_signals, quantum, executor = components
    try:
        await market_signals.cleanup()
        await executor.cleanup()
        quantum.cleanup()
        logging.info("Cleanup completed")
    except Exception as e:
        logging.error(f"Cleanup error: {str(e)}")

async def main():
    app = QApplication(sys.argv)
    components = None

    try:
        # Load config
        config = load_config()

        # Initialize components
        components = await initialize_components(config)
        gui, market_signals, quantum, executor = components

        # Start services
        await market_signals.start()
        quantum.start()

        # Show GUI
        gui.show()

        # Run event loop
        while True:
            app.processEvents()
            await asyncio.sleep(0.01)

    except Exception as e:
        logging.error(f"Fatal error: {str(e)}")
        if components:
            await cleanup_components(components)
        sys.exit(1)

    finally:
        if components:
            await cleanup_components(components)

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logging.info("Program terminated by user")
    except Exception as e:
        logging.error(f"Program crashed: {str(e)}")
        sys.exit(1) ADD MAXIMUM LOGGING