import pandas as pd
import ta
import logging

class SignalGenerator:
    def __init__(self, config):
        self.config = config
        self.latest_states = {}

    def generate_signal(self, symbol, df):
        if df is None or len(df) < self.config['strategy_params']['ema_long']:
            return "NEUTRAL", 0.0

        # Calculate Indicators
        ema_fast = ta.trend.ema_indicator(df['close'], window=self.config['strategy_params']['ema_fast'])
        ema_slow = ta.trend.ema_indicator(df['close'], window=self.config['strategy_params']['ema_slow'])
        ema_long = ta.trend.ema_indicator(df['close'], window=self.config['strategy_params']['ema_long'])
        rsi = ta.momentum.rsi(df['close'], window=self.config['strategy_params']['rsi_period'])

        current_price = df['close'].iloc[-1]
        last_rsi = rsi.iloc[-1]
        
        # Check Entry Rules
        # 1. EMA Cross
        ema_cross_up = ema_fast.iloc[-1] > ema_slow.iloc[-1] and ema_fast.iloc[-2] <= ema_slow.iloc[-2]
        ema_cross_down = ema_fast.iloc[-1] < ema_slow.iloc[-1] and ema_fast.iloc[-2] >= ema_slow.iloc[-2]
        
        # 2. RSI Confirmation
        is_oversold = last_rsi < self.config['strategy_params']['rsi_buy_threshold']
        is_overbought = last_rsi > self.config['strategy_params']['rsi_sell_threshold']

        # 3. Long Term Trend
        is_above_ema200 = current_price > ema_long.iloc[-1]

        signal = "NEUTRAL"
        confidence = 0.0

        if ema_cross_up and is_oversold and is_above_ema200:
            signal = "BUY"
            confidence = 0.8
        elif ema_cross_down or is_overbought:
            signal = "SELL"
            confidence = 0.7

        # Store latest state for dashboard
        self.latest_states[symbol] = {
            "price": current_price,
            "rsi": last_rsi,
            "ema_fast": ema_fast.iloc[-1],
            "ema_slow": ema_slow.iloc[-1],
            "ema_long": ema_long.iloc[-1],
            "signal": signal,
            "confidence": confidence,
            "volume": float(df['volume'].iloc[-1]) if 'volume' in df else 0.0,
            "timestamp": df['timestamp'].iloc[-1].isoformat() if 'timestamp' in df else None
        }

        logging.info(f"Signal for {symbol}: {signal} (Cnf: {confidence}) | RSI: {last_rsi:.2f} | Price: {current_price:.2f}")
        return signal, confidence
