import os
import requests
import logging

log = logging.getLogger("telegram_notifier")

class TelegramNotifier:
    def __init__(self):
        # Membaca token bot dan chat ID target dari environment
        self.bot_token = os.getenv("TELEGRAM_BOT_TOKEN")
        self.chat_id = os.getenv("TELEGRAM_CHAT_ID")
        self.enabled = bool(self.bot_token and self.chat_id)

    def send_message(self, text: str):
        """Mengirim pesan notifikasi ke Telegram."""
        if not self.enabled:
            log.warning("Telegram Notifier belum dikonfigurasi (TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID kosong).")
            return

        url = f"https://api.telegram.org/bot{self.bot_token}/sendMessage"
        payload = {
            "chat_id": self.chat_id,
            "text": text,
            "parse_mode": "HTML"
        }

        try:
            response = requests.post(url, json=payload, timeout=10)
            if response.status_code != 200:
                log.error(f"Gagal kirim notifikasi Telegram: {response.text}")
        except Exception as e:
            log.error(f"Error mengirim Telegram: {e}")

    def notify_trade_open(self, symbol, direction, price, sl, tp, lot_size):
        """Format khusus untuk open posisi."""
        icon = "🟢" if direction == "BUY" else "🔴"
        msg = (
            f"<b>{icon} SCALPING {direction}: {symbol}</b>\n"
            f"Harga: {price}\n"
            f"Lot: {lot_size}\n"
            f"SL: {sl}\n"
            f"TP: {tp}\n"
            f"#OpenPosition"
        )
        self.send_message(msg)

    def notify_trade_close(self, symbol, direction, close_price, profit, reason):
        """Format khusus untuk close posisi (Hit TP, SL, atau Trailing)."""
        icon = "💰" if profit > 0 else "💔"
        if reason == "BREAK_EVEN":
            icon = "🛡️"
            
        msg = (
            f"<b>{icon} TRADE CLOSED: {symbol}</b>\n"
            f"Direction: {direction}\n"
            f"Harga Tutup: {close_price}\n"
            f"Profit: ${profit:.2f}\n"
            f"Alasan: {reason}\n"
            f"#ClosePosition"
        )
        self.send_message(msg)
