import numpy as np
import logging
from dataclasses import dataclass
from datetime import datetime
from typing import Dict, Optional, List
from PyQt6.QtCore import QObject, pyqtSignal

@dataclass
class TradeSignal:
    token_mint: str
    direction: int
    price: float
    volume_5m: float
    buyer_ratio: float
    confidence: float
    timestamp: datetime
    size: float = 0.0
    current_profit: float = 0.0

class SignalEmitter(QObject):
    trade_signal = pyqtSignal(object)
    price_update = pyqtSignal(float)
    volume_update = pyqtSignal(float)
    connection_update = pyqtSignal(bool)
    pool_update = pyqtSignal(dict)
    metrics_update = pyqtSignal(dict)
    neural_update = pyqtSignal(dict)
    error_signal = pyqtSignal(str)
    prediction_update = pyqtSignal(dict)

    def __init__(self):
        super().__init__()

class SignalProcessor:
    def __init__(self, config: Dict):
        self.config = config
        self.signals = SignalEmitter()
        self.min_volume = float(config["trading"]["min_volume"])
        self.min_bs_ratio = float(config["trading"]["min_bs_ratio"])
        self.stop_loss = float(config["risk"]["stop_loss"]) / 100
        self.initial_size = float(config["trading"]["initial_size"])
        self.active_positions = {}
        self.active_pools = {}
        self.top_pools = []
        self.data_buffer: List[Dict] = []
        self.logger = logging.getLogger(__name__)
        self.initialized = True
        self.current_data = None

    async def get_trading_signal(self):
        """Async method for getting trading signals"""
        if not self.current_data:
            return None
            
        try:
            volume_score = min(self.current_data["volume_5m"] / self.min_volume, 1.0)
            ratio_score = min(self.current_data["buyer_ratio"] / self.min_bs_ratio, 1.0)
            confidence = (volume_score + ratio_score) / 2
            
            return {
                "direction": 1 if self.current_data["buyer_ratio"] > self.min_bs_ratio else -1,
                "confidence": confidence,
                "price": self.current_data["price"],
                "volume": self.current_data["volume_5m"],
                "token_mint": self.current_data["mint_address"]
            }
        except Exception as e:
            self.logger.error(f"Signal generation error: {e}")
            return None

    async def process_data_async(self, data: Dict):
        """Process data asynchronously"""
        if not data:
            return None
            
        self.current_data = data
        return await self.process_pool_data(data)

    async def process_pool_data(self, data: Dict):
        """Process pool data with proper error handling"""
        try:
            if not isinstance(data, dict) or 'mint_address' not in data:
                return None

            pool_data = {
                "mint_address": data["mint_address"],
                "volume_5m": float(data.get("volume_5m", 0)),
                "buyer_ratio": float(data.get("buyer_ratio", 0)),
                "price": float(data.get("price", 0))
            }

            self.signals.price_update.emit(pool_data["price"])
            self.signals.volume_update.emit(pool_data["volume_5m"])
            self.signals.pool_update.emit(pool_data)

            if await self._is_valid_entry(pool_data):
                signal = await self._generate_trade_signal(pool_data)
                if signal:
                    self.signals.trade_signal.emit(signal)
                return signal

            return None

        except Exception as e:
            self.logger.error(f"Pool data processing error: {e}")
            return None

    async def _is_valid_entry(self, pool_data: Dict) -> bool:
        """Validate entry conditions"""
        return (
            pool_data["volume_5m"] >= self.min_volume and
            pool_data["buyer_ratio"] >= self.min_bs_ratio and
            pool_data["price"] > 0
        )

    async def _generate_trade_signal(self, pool_data: Dict) -> Optional[TradeSignal]:
        """Generate trade signal with confidence calculation"""
        try:
            volume_score = min(pool_data["volume_5m"] / self.min_volume, 5.0)
            ratio_score = min(pool_data["buyer_ratio"] / self.min_bs_ratio, 5.0)
            confidence = (0.6 * volume_score + 0.4 * ratio_score) / 5.0
            
            return TradeSignal(
                token_mint=pool_data["mint_address"],
                direction=1 if pool_data["buyer_ratio"] > self.min_bs_ratio * 1.2 else -1,
                price=pool_data["price"],
                volume_5m=pool_data["volume_5m"],
                buyer_ratio=pool_data["buyer_ratio"],
                confidence=confidence,
                timestamp=datetime.now(),
                size=self.initial_size
            )
        except Exception as e:
            self.logger.error(f"Signal generation error: {e}")
            return None

    def update_position(self, token_mint: str, trade_result: Dict):
        """Update position tracking"""
        if trade_result["success"]:
            if trade_result["is_buy"]:
                self.active_positions[token_mint] = {
                    "entry_price": trade_result["price"],
                    "size": trade_result["size"],
                    "timestamp": datetime.now()
                }
            else:
                self.active_positions.pop(token_mint, None)

    async def cleanup(self):
        """Async cleanup method"""
        self.active_positions.clear()
        self.active_pools.clear()
        self.top_pools.clear()
        self.data_buffer.clear()
        self.current_data = None
        self.initialized = False
        return True
 ADD MAXIMUM LOGGING