"""
Module de notifications Telegram pour le bot de trading
Inspiré de: https://github.com/Erfaniaa/binance-futures-trading-bot
"""
import asyncio
import logging
from datetime import datetime

# Import conditionnel de telegram
try:
    import telegram
    TELEGRAM_AVAILABLE = True
except ImportError:
    TELEGRAM_AVAILABLE = False
    logging.warning("⚠️ Module python-telegram-bot non installé. Installez avec: pip install python-telegram-bot")

class TelegramNotifier:
    """
    Service de notifications Telegram pour alertes de trading
    """

    def __init__(self, api_key=None, chat_id=None, enabled=False):
        self.enabled = enabled and TELEGRAM_AVAILABLE
        self.api_key = api_key
        self.chat_id = chat_id
        self.bot = None

        if self.enabled and api_key and chat_id:
            try:
                self.bot = telegram.Bot(token=api_key)
                logging.info("✅ Telegram notifier initialisé")
            except Exception as e:
                logging.error(f"❌ Erreur initialisation Telegram: {e}")
                self.enabled = False

    async def send_message(self, message, parse_mode='Markdown'):
        """Envoie un message Telegram"""
        if not self.enabled or not self.bot:
            return False

        try:
            await self.bot.send_message(
                chat_id=self.chat_id,
                text=message,
                parse_mode=parse_mode
            )
            return True
        except Exception as e:
            logging.error(f"❌ Erreur envoi Telegram: {e}")
            return False

    def send_message_sync(self, message, parse_mode='Markdown'):
        """Version synchrone pour compatibilité"""
        if not self.enabled:
            return False
        try:
            loop = asyncio.get_event_loop()
            if loop.is_running():
                asyncio.create_task(self.send_message(message, parse_mode))
            else:
                loop.run_until_complete(self.send_message(message, parse_mode))
            return True
        except Exception as e:
            logging.error(f"❌ Erreur envoi sync Telegram: {e}")
            return False

    # ═══════════════════════════════════════════════════════════════════════
    # MESSAGES PRÉDÉFINIS POUR ÉVÉNEMENTS DE TRADING
    # ═══════════════════════════════════════════════════════════════════════

    async def notify_buy_order(self, symbol, price, quantity, reason=""):
        """Notification d'ordre d'achat"""
        timestamp = datetime.now().strftime("%H:%M:%S")
        message = f"""
🟢 *ACHAT EXÉCUTÉ* 🟢
━━━━━━━━━━━━━━━━━━
📊 Crypto: `{symbol}`
💰 Prix: `{price:.6f} USDT`
📦 Quantité: `{quantity:.6f}`
⏰ Heure: `{timestamp}`
"""
        if reason:
            message += f"📝 Raison: `{reason}`\n"

        await self.send_message(message)

    async def notify_sell_order(self, symbol, price, quantity, profit_pct, reason=""):
        """Notification d'ordre de vente"""
        timestamp = datetime.now().strftime("%H:%M:%S")
        emoji = "🟢" if profit_pct >= 0 else "🔴"
        status = "PROFIT" if profit_pct >= 0 else "PERTE"

        message = f"""
{emoji} *VENTE EXÉCUTÉE* {emoji}
━━━━━━━━━━━━━━━━━━
📊 Crypto: `{symbol}`
💰 Prix: `{price:.6f} USDT`
📦 Quantité: `{quantity:.6f}`
📈 P&L: `{profit_pct:+.2f}%` ({status})
⏰ Heure: `{timestamp}`
"""
        if reason:
            message += f"📝 Raison: `{reason}`\n"

        await self.send_message(message)

    async def notify_stop_loss(self, symbol, price, loss_pct):
        """Notification de déclenchement stop-loss"""
        timestamp = datetime.now().strftime("%H:%M:%S")
        message = f"""
🛑 *STOP-LOSS DÉCLENCHÉ* 🛑
━━━━━━━━━━━━━━━━━━
📊 Crypto: `{symbol}`
💰 Prix: `{price:.6f} USDT`
📉 Perte: `{loss_pct:.2f}%`
⏰ Heure: `{timestamp}`
"""
        await self.send_message(message)

    async def notify_take_profit(self, symbol, price, profit_pct):
        """Notification de déclenchement take-profit"""
        timestamp = datetime.now().strftime("%H:%M:%S")
        message = f"""
✅ *TAKE-PROFIT ATTEINT* ✅
━━━━━━━━━━━━━━━━━━
📊 Crypto: `{symbol}`
💰 Prix: `{price:.6f} USDT`
📈 Profit: `+{profit_pct:.2f}%`
⏰ Heure: `{timestamp}`
"""
        await self.send_message(message)

    async def notify_error(self, error_message):
        """Notification d'erreur critique"""
        message = f"""
⚠️ *ERREUR CRITIQUE* ⚠️
━━━━━━━━━━━━━━━━━━
{error_message}
"""
        await self.send_message(message)

    async def notify_daily_summary(self, total_trades, wins, losses, total_profit_pct, balance):
        """Résumé quotidien des performances"""
        win_rate = (wins / total_trades * 100) if total_trades > 0 else 0
        emoji = "📈" if total_profit_pct >= 0 else "📉"

        message = f"""
{emoji} *RÉSUMÉ QUOTIDIEN* {emoji}
━━━━━━━━━━━━━━━━━━
📊 Trades: `{total_trades}`
✅ Gagnants: `{wins}` ({win_rate:.1f}%)
❌ Perdants: `{losses}`
💰 P&L Total: `{total_profit_pct:+.2f}%`
💵 Solde: `{balance:.2f} USDT`
"""
        await self.send_message(message)

    async def notify_bot_started(self, watchlist_count, balance):
        """Notification de démarrage du bot"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        message = f"""
🤖 *BOT DÉMARRÉ* 🤖
━━━━━━━━━━━━━━━━━━
⏰ Heure: `{timestamp}`
📋 Cryptos surveillées: `{watchlist_count}`
💵 Solde initial: `{balance:.2f} USDT`
━━━━━━━━━━━━━━━━━━
✅ Système opérationnel
"""
        await self.send_message(message)

    async def notify_bot_stopped(self, reason="Arrêt manuel"):
        """Notification d'arrêt du bot"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        message = f"""
🛑 *BOT ARRÊTÉ* 🛑
━━━━━━━━━━━━━━━━━━
⏰ Heure: `{timestamp}`
📝 Raison: `{reason}`
"""
        await self.send_message(message)


# Instance globale (sera initialisée par le bot principal)
telegram_notifier = None

def init_telegram_notifier(api_key, chat_id, enabled=True):
    """Initialise le notifier Telegram global"""
    global telegram_notifier
    telegram_notifier = TelegramNotifier(api_key, chat_id, enabled)
    return telegram_notifier

def get_telegram_notifier():
    """Récupère l'instance du notifier"""
    return telegram_notifier
