import logging
import asyncio
from typing import Optional
from telegram import Bot, Update
from telegram.ext import Application, CommandHandler, ContextTypes
from app.config import settings

logger = logging.getLogger(__name__)


class TelegramService:
    """
    Sends trade alerts to a Telegram chat.
    Also handles /status, /pause, /resume commands.
    """

    def __init__(self):
        self._bot: Optional[Bot] = None
        self._app: Optional[Application] = None
        self._bot_running = True  # external pause flag

    def _get_bot(self) -> Optional[Bot]:
        if not settings.TELEGRAM_BOT_TOKEN:
            return None
        if self._bot is None:
            self._bot = Bot(token=settings.TELEGRAM_BOT_TOKEN)
        return self._bot

    async def send_message(self, text: str):
        """Send a plain-text message to the configured Telegram chat."""
        bot = self._get_bot()
        if bot is None or not settings.TELEGRAM_CHAT_ID:
            logger.debug("Telegram not configured, skipping message")
            return
        try:
            await bot.send_message(
                chat_id=settings.TELEGRAM_CHAT_ID,
                text=text,
                parse_mode="HTML",
            )
        except Exception as e:
            logger.error(f"Telegram send error: {e}")

    async def notify_trade_opened(self, trade):
        text = (
            f"<b>Trade Opened</b>\n"
            f"Pair: {trade.pair}\n"
            f"Signal: {trade.signal}\n"
            f"Mode: {trade.mode}\n"
            f"Entry: {trade.entry_price}\n"
            f"SL: {trade.stop_loss}\n"
            f"TP1: {trade.take_profit_levels[0] if trade.take_profit_levels else 'N/A'}\n"
            f"TP2: {trade.take_profit_levels[1] if len(trade.take_profit_levels) > 1 else 'N/A'}"
        )
        await self.send_message(text)

    async def notify_trade_closed(self, trade):
        emoji = "WIN" if trade.result == "WIN" else "LOSS"
        text = (
            f"<b>Trade Closed — {emoji}</b>\n"
            f"Pair: {trade.pair}\n"
            f"Signal: {trade.signal}\n"
            f"Entry: {trade.entry_price}\n"
            f"Exit: {trade.current_price}\n"
            f"PnL: {trade.pnl_percentage:.2f}%"
        )
        await self.send_message(text)

    async def notify_sl_hit(self, trade):
        text = (
            f"<b>Stop Loss Hit</b>\n"
            f"Pair: {trade.pair} | Signal: {trade.signal}\n"
            f"Entry: {trade.entry_price} | SL: {trade.stop_loss}\n"
            f"PnL: {trade.pnl_percentage:.2f}%"
        )
        await self.send_message(text)

    async def notify_tp_hit(self, trade, tp_index: int):
        text = (
            f"<b>Take Profit {tp_index + 1} Hit</b>\n"
            f"Pair: {trade.pair} | Signal: {trade.signal}\n"
            f"TP{tp_index+1}: {trade.take_profit_levels[tp_index]}"
        )
        await self.send_message(text)

    def start_command_listener(self):
        """
        Start the Telegram bot command listener in the background.
        Supports: /status, /pause, /resume
        """
        if not settings.TELEGRAM_BOT_TOKEN:
            logger.info("Telegram token not set, command listener not started")
            return

        async def status_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
            state = "RUNNING" if self._bot_running else "PAUSED"
            await update.message.reply_text(f"Bot status: {state}")

        async def pause_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
            self._bot_running = False
            await update.message.reply_text("Bot PAUSED. New trades will not be opened.")

        async def resume_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
            self._bot_running = True
            await update.message.reply_text("Bot RESUMED. Trading active.")

        async def run():
            app = Application.builder().token(settings.TELEGRAM_BOT_TOKEN).build()
            app.add_handler(CommandHandler("status", status_handler))
            app.add_handler(CommandHandler("pause", pause_handler))
            app.add_handler(CommandHandler("resume", resume_handler))
            self._app = app
            await app.initialize()
            await app.start()
            await app.updater.start_polling()

        asyncio.create_task(run())

    @property
    def is_running(self) -> bool:
        return self._bot_running


telegram_service = TelegramService()
