from analysis.risk_management import calculate_sl_tp, calculate_risk_reward

class GenerateSignal:
	def __init__(self):
		self.__init__
		
	def generate_signals(self, df, symbol, provider, lot_size=1):
		if provider == "alphavantage":
			return self.__alpha_vantage_signal(df, symbol, lot_size);

		return None

	def __alpha_vantage_signal(self, df, symbol, lot_size=1):
			signals = []

			close_price = df['Close'].iloc[-1]
			
			atr_value = df['ATR'].iloc[-1] if 'ATR' in df.columns else None

			if atr_value is None:
					raise ValueError("ATR not available. Ensure indicators are calculated correctly.")

			# SMA Crossover Signal
			sma_50 = df['SMA_50'].iloc[-1] if 'SMA_50' in df.columns else None
			sma_200 = df['SMA_200'].iloc[-1] if 'SMA_200' in df.columns else None
			if sma_50 is not None and sma_200 is not None:
					if sma_50 > sma_200 * 1.005:  # Bullish crossover
							sl_price, tp_price = calculate_sl_tp(close_price, atr_value, symbol, signal_type="buy")
							monetary_risk, monetary_reward = calculate_risk_reward(close_price, sl_price, tp_price, lot_size)
							signals.append("Bullish SMA Crossover: Buy Signal\n"
														f"Entry Price: {close_price:.4f}\n"
														f"Stop-Loss (SL): {sl_price:.4f} ({50} pips)\n"
														f"Take-Profit (TP): {tp_price:.4f} ({100} pips)\n"
														f"Monetary Risk: ${monetary_risk:.2f}, Monetary Reward: ${monetary_reward:.2f}\n\n"
														"Explanation: The 50-day SMA has crossed above the 200-day SMA, indicating "
														"that short-term momentum is strengthening compared to long-term momentum. "
														"This is a bullish signal suggesting an uptrend may be starting.\n\n"
														"Risk Management Tip: Set SL below recent support levels.\n\n"
														"=====================================\n\n")
					elif sma_50 < sma_200 * 0.995:  # Bearish crossover
							sl_price, tp_price = calculate_sl_tp(close_price, atr_value, symbol, signal_type="sell")
							monetary_risk, monetary_reward = calculate_risk_reward(close_price, sl_price, tp_price, lot_size)
							signals.append("Bearish SMA Crossover: Sell Signal\n"
														f"Entry Price: {close_price:.4f}\n"
														f"Stop-Loss (SL): {sl_price:.4f} ({50} pips)\n"
														f"Take-Profit (TP): {tp_price:.4f} ({100} pips)\n"
														f"Monetary Risk: ${monetary_risk:.2f}, Monetary Reward: ${monetary_reward:.2f}\n\n"
														"Explanation: The 50-day SMA has crossed below the 200-day SMA, indicating "
														"that short-term momentum is weakening compared to long-term momentum. "
														"This is a bearish signal suggesting a downtrend may be starting.\n\n"
														"Risk Management Tip: Set SL above recent resistance levels.\n\n"
														"=====================================\n\n")

			# RSI Signal
			rsi = df['RSI'].iloc[-1] if 'RSI' in df.columns else None
			if rsi is not None:
					if rsi > 70:  # Overbought
							sl_price, tp_price = calculate_sl_tp(close_price, atr_value, symbol, signal_type="sell")
							monetary_risk, monetary_reward = calculate_risk_reward(close_price, sl_price, tp_price, lot_size)
							signals.append("Overbought RSI: Sell Signal\n"
														f"Entry Price: {close_price:.4f}\n"
														f"Stop-Loss (SL): {sl_price:.4f} ({50} pips)\n"
														f"Take-Profit (TP): {tp_price:.4f} ({100} pips)\n"
														f"Monetary Risk: ${monetary_risk:.2f}, Monetary Reward: ${monetary_reward:.2f}\n\n"
														"Explanation: The RSI is above 70, indicating that the asset is overbought. "
														"This suggests that the price may be due for a pullback or correction, "
														"and selling pressure could increase.\n\n"
														"Risk Management Tip: Avoid entering new long positions until the RSI drops below 70.\n\n"
														"=====================================\n\n")
					elif rsi < 30:  # Oversold
							sl_price, tp_price = calculate_sl_tp(close_price, atr_value, symbol, signal_type="buy")
							monetary_risk, monetary_reward = calculate_risk_reward(close_price, sl_price, tp_price, lot_size)
							signals.append("Oversold RSI: Buy Signal\n"
														f"Entry Price: {close_price:.4f}\n"
														f"Stop-Loss (SL): {sl_price:.4f} ({50} pips)\n"
														f"Take-Profit (TP): {tp_price:.4f} ({100} pips)\n"
														f"Monetary Risk: ${monetary_risk:.2f}, Monetary Reward: ${monetary_reward:.2f}\n\n"
														"Explanation: The RSI is below 30, indicating that the asset is oversold. "
														"This suggests that the price may be due for a rebound, and buying pressure "
														"could increase.\n\n"
														"Risk Management Tip: Wait for confirmation (e.g., price breaking above resistance).\n\n"
														"=====================================\n\n")

			# Bollinger Bands Signal
			upper_band = df['BBU_20_2.0'].iloc[-1] if 'BBU_20_2.0' in df.columns else None
			lower_band = df['BBL_20_2.0'].iloc[-1] if 'BBL_20_2.0' in df.columns else None
			if close_price is not None and upper_band is not None and lower_band is not None:
					if close_price > upper_band * 1.005:  # Price above upper band
							sl_price, tp_price = calculate_sl_tp(close_price, atr_value, symbol, signal_type="sell")
							monetary_risk, monetary_reward = calculate_risk_reward(close_price, sl_price, tp_price, lot_size)
							signals.append("Price above Upper Bollinger Band: Sell Signal\n"
														f"Entry Price: {close_price:.4f}\n"
														f"Stop-Loss (SL): {sl_price:.4f} ({50} pips)\n"
														f"Take-Profit (TP): {tp_price:.4f} ({100} pips)\n"
														f"Monetary Risk: ${monetary_risk:.2f}, Monetary Reward: ${monetary_reward:.2f}\n\n"
														"Explanation: The price is above the upper Bollinger Band, indicating "
														"that the asset may be overextended and due for a pullback. "
														"This is a bearish signal suggesting potential selling pressure.\n\n"
														"Risk Management Tip: Consider reducing exposure or exiting long positions.\n\n"
														"=====================================\n\n")
					elif close_price < lower_band * 0.995:  # Price below lower band
							sl_price, tp_price = calculate_sl_tp(close_price, atr_value, symbol, signal_type="buy")
							monetary_risk, monetary_reward = calculate_risk_reward(close_price, sl_price, tp_price, lot_size)
							signals.append("Price below Lower Bollinger Band: Buy Signal\n"
														f"Entry Price: {close_price:.4f}\n"
														f"Stop-Loss (SL): {sl_price:.4f} ({50} pips)\n"
														f"Take-Profit (TP): {tp_price:.4f} ({100} pips)\n"
														f"Monetary Risk: ${monetary_risk:.2f}, Monetary Reward: ${monetary_reward:.2f}\n\n"
														"Explanation: The price is below the lower Bollinger Band, indicating "
														"that the asset may be oversold and due for a rebound. "
														"This is a bullish signal suggesting potential buying pressure.\n\n"
														"Risk Management Tip: Use a tight stop-loss to limit downside risk.\n\n"
														"=====================================\n\n")

			# MACD Signal
			macd_line = df['MACD_12_26_9'].iloc[-1] if 'MACD_12_26_9' in df.columns else None
			signal_line = df['MACDs_12_26_9'].iloc[-1] if 'MACDs_12_26_9' in df.columns else None
			if macd_line is not None and signal_line is not None:
					if macd_line > signal_line * 1.005:  # Bullish crossover
							sl_price, tp_price = calculate_sl_tp(close_price, atr_value, symbol, signal_type="buy")
							monetary_risk, monetary_reward = calculate_risk_reward(close_price, sl_price, tp_price, lot_size)
							signals.append("MACD Bullish Crossover: Buy Signal\n"
														f"Entry Price: {close_price:.4f}\n"
														f"Stop-Loss (SL): {sl_price:.4f} ({50} pips)\n"
														f"Take-Profit (TP): {tp_price:.4f} ({100} pips)\n"
														f"Monetary Risk: ${monetary_risk:.2f}, Monetary Reward: ${monetary_reward:.2f}\n\n"
														"Explanation: The MACD Line has crossed above the Signal Line, indicating "
														"that short-term momentum is strengthening compared to long-term momentum. "
														"This is a bullish signal suggesting an uptrend may be starting.\n\n"
														"Risk Management Tip: Confirm with other indicators (e.g., RSI, Bollinger Bands).\n\n"
														"=====================================\n\n")
					elif macd_line < signal_line * 0.995:  # Bearish crossover
							sl_price, tp_price = calculate_sl_tp(close_price, atr_value, symbol, signal_type="sell")
							monetary_risk, monetary_reward = calculate_risk_reward(close_price, sl_price, tp_price, lot_size)
							signals.append("MACD Bearish Crossover: Sell Signal\n"
														f"Entry Price: {close_price:.4f}\n"
														f"Stop-Loss (SL): {sl_price:.4f} ({50} pips)\n"
														f"Take-Profit (TP): {tp_price:.4f} ({100} pips)\n"
														f"Monetary Risk: ${monetary_risk:.2f}, Monetary Reward: ${monetary_reward:.2f}\n\n"
														"Explanation: The MACD Line has crossed below the Signal Line, indicating "
														"that short-term momentum is weakening compared to long-term momentum. "
														"This is a bearish signal suggesting a downtrend may be starting.\n\n"
														"Risk Management Tip: Avoid entering new trades until the trend reverses.\n\n"
														"=====================================\n\n")

			# Combined Buy Signal
			rsi_buy = df['RSI'].iloc[-1] < 30 if 'RSI' in df.columns else False
			bollinger_buy = df['Close'].iloc[-1] < df['BBL_20_2.0'].iloc[-1] if 'BBL_20_2.0' in df.columns else False
			macd_buy = df['MACD_12_26_9'].iloc[-1] > df['MACDs_12_26_9'].iloc[-1] if 'MACD_12_26_9' in df.columns else False
			if rsi_buy and bollinger_buy and macd_buy:
					sl_price, tp_price = calculate_sl_tp(close_price, atr_value, symbol, signal_type="buy")
					monetary_risk, monetary_reward = calculate_risk_reward(close_price, sl_price, tp_price, lot_size)
					signals.append("Advanced Buy Signal: RSI Oversold, Below Bollinger Band, MACD Bullish Crossover\n"
												f"Entry Price: {close_price:.4f}\n"
												f"Stop-Loss (SL): {sl_price:.4f} ({50} pips)\n"
												f"Take-Profit (TP): {tp_price:.4f} ({100} pips)\n"
												f"Monetary Risk: ${monetary_risk:.2f}, Monetary Reward: ${monetary_reward:.2f}\n\n"
												"Explanation: Multiple indicators suggest a strong buy signal. The RSI is oversold, "
												"the price is below the lower Bollinger Band, and the MACD shows bullish momentum. "
												"This combination indicates a high probability of an upward move.\n\n"
												"Risk Management Tip: Use a trailing stop-loss to lock in profits as the price rises.\n\n"
												"=====================================\n\n")

					# Combined Sell Signal
			rsi_sell = df['RSI'].iloc[-1] > 70 if 'RSI' in df.columns else False
			bollinger_sell = df['Close'].iloc[-1] > df['BBU_20_2.0'].iloc[-1] if 'BBU_20_2.0' in df.columns else False
			macd_sell = df['MACD_12_26_9'].iloc[-1] < df['MACDs_12_26_9'].iloc[-1] if 'MACD_12_26_9' in df.columns else False
			if rsi_sell and bollinger_sell and macd_sell:
					sl_price, tp_price = calculate_sl_tp(close_price, atr_value, symbol, signal_type="sell")
					monetary_risk, monetary_reward = calculate_risk_reward(close_price, sl_price, tp_price, lot_size)
					signals.append("Advanced Sell Signal: RSI Overbought, Above Bollinger Band, MACD Bearish Crossover\n"
												f"Entry Price: {close_price:.4f}\n"
												f"Stop-Loss (SL): {sl_price:.4f} ({50} pips)\n"
												f"Take-Profit (TP): {tp_price:.4f} ({100} pips)\n"
														f"Monetary Risk: ${monetary_risk:.2f}, Monetary Reward: ${monetary_reward:.2f}\n\n"
												"Explanation: Multiple indicators suggest a strong sell signal. The RSI is overbought, "
												"the price is above the upper Bollinger Band, and the MACD shows bearish momentum. "
												"This combination indicates a high probability of a downward move.\n\n"
												"Risk Management Tip: Exit long positions and consider shorting if appropriate.\n\n"
												"=====================================\n\n")

			# Highlight Conflicting Signals
			if len(signals) > 1:
					signals.append("\n⚠️ Note: Conflicting signals detected. Use caution and monitor price action for confirmation.")

			return signals