import requests
from dotenv import load_dotenv
import os
load_dotenv()


def send_message(message):
    """Send a text message to the configured Telegram chat."""
    
    TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
    TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
    
    # Check if credentials are loaded
    if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
        print("❌ Error: TELEGRAM_BOT_TOKEN or TELEGRAM_CHAT_ID not found in .env file")
        return None
    
    token = TELEGRAM_BOT_TOKEN
    chat_id = TELEGRAM_CHAT_ID
    url = f"https://api.telegram.org/bot{token}/sendMessage"

    try:
        response = requests.post(
            url,
            data={
                "chat_id": chat_id,
                "text": message
            },
            timeout=10
        )
        
        result = response.json()
        
        # Check if message was sent successfully
        if result.get("ok"):
            print(f"✓ Message sent successfully to chat {chat_id}")
            return result
        else:
            error_msg = result.get("description", "Unknown error")
            print(f"❌ Failed to send message: {error_msg}")
            return result
            
    except requests.exceptions.RequestException as e:
        print(f"❌ Connection error: {e}")
        return None


# Test the bot - uncomment to run
if __name__ == "__main__":
    send_message("Hello from the bot! 🤖")