import requests
import logging
from config import load_config

logger = logging.getLogger("TELEGRAM")

class TelegramNotifier:
    def __init__(self):
        self.config = load_config()
        self.bot_token = self.config.get('telegram', {}).get('bot_token', '')
        self.chat_id = self.config.get('telegram', {}).get('chat_id', '')

    def reload_config(self):
        self.config = load_config()
        self.bot_token = self.config.get('telegram', {}).get('bot_token', '')
        self.chat_id = self.config.get('telegram', {}).get('chat_id', '')

    def send_message(self, text):
        # Reload to ensure we have latest from settings
        self.reload_config()
        
        # Check if enabled
        if not self.config.get('preferences', {}).get('enable_telegram', True):
            return

        if not self.bot_token or not self.chat_id:
            logger.warning("Telegram credentials missing.")
            return

        url = f"https://api.telegram.org/bot{self.bot_token}/sendMessage"
        payload = {
            "chat_id": self.chat_id,
            "text": text
        }
        
        try:
            res = requests.post(url, json=payload, timeout=5)
            if res.status_code != 200:
                logger.error(f"Telegram Send Failed: {res.text}")
        except Exception as e:
            logger.error(f"Telegram Error: {e}")

notifier = TelegramNotifier()
