# ═══════════════════════════════════════════════════════════════
#  notifier.py — Notificações via Telegram
#  Tutorial setup: t.me/BotFather → /newbot
# ═══════════════════════════════════════════════════════════════

import requests
import logging
from datetime import datetime
import config as cfg

logger = logging.getLogger("BotBTC.Notifier")


class Notifier:
    def __init__(self):
        self.ativo    = cfg.TELEGRAM_ATIVO
        self.token    = cfg.TELEGRAM_TOKEN
        self.chat_id  = cfg.TELEGRAM_CHAT_ID
        self.base_url = f"https://api.telegram.org/bot{self.token}"

    def _enviar(self, msg: str):
        if not self.ativo:
            return
        try:
            requests.post(
                f"{self.base_url}/sendMessage",
                json={"chat_id": self.chat_id, "text": msg, "parse_mode": "HTML"},
                timeout=10
            )
        except Exception as e:
            logger.warning(f"Telegram erro: {e}")

    def compra(self, preco: float, qtd: float, stop: float, alvo1: float, alvo2: float, score: int):
        self._enviar(
            f"🟢 <b>COMPRA EXECUTADA — BTC/USDT</b>\n"
            f"💰 Preço: <code>${preco:,.2f}</code>\n"
            f"📦 Quantidade: <code>{qtd:.5f} BTC</code>\n"
            f"🛑 Stop Loss: <code>${stop:,.2f}</code>\n"
            f"🎯 Alvo 1: <code>${alvo1:,.2f}</code>\n"
            f"🏆 Alvo 2: <code>${alvo2:,.2f}</code>\n"
            f"📊 Score: <code>{score}/10</code>\n"
            f"⏰ {datetime.now().strftime('%d/%m %H:%M:%S')}"
        )

    def venda(self, preco: float, qtd: float, motivo: str, pnl: float, pnl_pct: float, capital: float):
        emoji = "✅" if pnl >= 0 else "❌"
        self._enviar(
            f"{emoji} <b>SAÍDA — {motivo}</b>\n"
            f"💰 Preço: <code>${preco:,.2f}</code>\n"
            f"📦 Quantidade: <code>{qtd:.5f} BTC</code>\n"
            f"📈 P&L: <code>{'+'if pnl>=0 else ''}{pnl:.2f} ({pnl_pct:.2f}%)</code>\n"
            f"💼 Capital: <code>${capital:.2f}</code>\n"
            f"⏰ {datetime.now().strftime('%d/%m %H:%M:%S')}"
        )

    def alvo1(self, preco: float, novo_stop: float):
        self._enviar(
            f"🎯 <b>ALVO 1 ATINGIDO!</b>\n"
            f"💰 Preço: <code>${preco:,.2f}</code>\n"
            f"🛡️ Stop movido para: <code>${novo_stop:,.2f}</code> (break-even)\n"
            f"⏰ {datetime.now().strftime('%d/%m %H:%M:%S')}"
        )

    def relatorio_diario(self, status: dict):
        emoji = "📈" if status["pnl_hoje"] >= 0 else "📉"
        self._enviar(
            f"{emoji} <b>RELATÓRIO DIÁRIO</b>\n"
            f"💼 Capital: <code>${status['capital']:,.2f}</code>\n"
            f"💰 P&L hoje: <code>{'+'if status['pnl_hoje']>=0 else ''}{status['pnl_hoje']:.2f}</code>\n"
            f"📊 P&L total: <code>{'+'if status['pnl_total']>=0 else ''}{status['pnl_total']:.2f}</code>\n"
            f"🎯 Win Rate: <code>{status['win_rate']}%</code>\n"
            f"📋 Trades hoje: <code>{status['trades_hoje']}</code>\n"
            f"✅ Wins: {status['wins']} | ❌ Losses: {status['losses']}"
        )

    def erro(self, mensagem: str):
        self._enviar(f"⚠️ <b>ERRO NO BOT</b>\n<code>{mensagem}</code>\n⏰ {datetime.now().strftime('%d/%m %H:%M:%S')}")

    def inicio(self, modo: str):
        self._enviar(
            f"🤖 <b>BOT BTC/USDT INICIADO</b>\n"
            f"⚙️ Modo: <code>{'📝 PAPER (simulação)' if modo == 'PAPER' else '💸 REAL'}</code>\n"
            f"📊 Timeframe: <code>{cfg.TIMEFRAME}</code>\n"
            f"💼 Capital: <code>${cfg.CAPITAL_TOTAL:,.2f}</code>\n"
            f"⏰ {datetime.now().strftime('%d/%m %H:%M:%S')}"
        )
