import os
import time
import logging
import subprocess
import telebot
import google.generativeai as genai

# Logging සෙට් කිරීම
logging.basicConfig(level=logging.INFO)

# 🔑 ඔන්න උඹ දීපු අලුත්ම Telegram Bot Token එක දැම්මා!
BOT_TOKEN = "8998263673:AAF3AZmu9WtgNLxRFeoW93yK7yh2qs_wEME"

# 🔑 ඔන්න උඹ දීපු අලුත්ම Gemini API Key එක දැම්මා!
GEMINI_API_KEY = "AIzaSyC01BkW42vpWBLsmm24aVU5F0NegqKOgMY"

# බොටා සහ Gemini සෙට් කිරීම
bot = telebot.TeleBot(BOT_TOKEN)
genai.configure(api_key=GEMINI_API_KEY)
model = genai.GenerativeModel(model_name="gemini-1.5-flash")

# /start කමාන්ඩ් එක වැදුණාම ක්‍රියාත්මක වන කොටස
@bot.message_handler(commands=['start'])
def send_welcome(message):
    user_name = message.from_user.first_name
    bot.reply_to(
        message, 
        f"හලෝ {user_name} මචං! 👋\n\nඔන්න මම දැන් කිසිම ලෙඩක් නැතුව 100%ක්ම ලයිව්! 🦾🔥\n\n"
        "දැන් මගෙන් ඕනෑම ප්‍රශ්නයක් අහපන්, මම Gemini AI එකෙන් හිතලා සිංහලෙන්ම උත්තර දෙන්නම්!"
    )

# සාමාන්‍ය මැසේජ් හැන්ඩ්ල් කරන කොටස
@bot.message_handler(func=lambda message: True)
def handle_all_messages(message):
    user_text = message.text
    # බොටා උත්තරය ටයිප් කරනවා වගේ පෙන්වීම (Typing Effect)
    bot.send_chat_action(message.chat.id, 'typing')
    
    try:
        # බොටාගේ කැරැක්ටර් එක Prompt එකෙන් සෙට් කරනවා
        prompt = f"ඔයාගේ නම Lanka AI Bot. ඔයා ලංකාවේ යාළුවෙක් වගේ ඉතාමත් සුහදශීලීව සිංහලෙන් උදව් කරන්න ඕනේ. කෙටියෙන් සහ පැහැදිලිව උත්තර දෙන්න. ප්‍රශ්නය: {user_text}"
        response = model.generate_content(prompt)
        reply = response.text
    except Exception as e:
        logging.error(f"Gemini Error: {e}")
        reply = "අයියෝ මචං, පොඩි සර්වර් අවුලක් ආවා. පොඩ්ඩක් ඉඳලා ආයෙත් අහන්නකෝ! 🙇‍♂️"
        
    bot.reply_to(message, reply)

if __name__ == '__main__':
    # Hugging Face එකට ඕන කරන Port 7860 වෙබ් පිටුව background එකේ ඕපන් කරලා තියනවා
    subprocess.Popen(["python", "-m", "http.server", "7860"])
    logging.info("Hugging Face Health Server started on port 7860...")
    
    # බොටා පණ ගැන්වීම (කවදාවත් හිරවෙන්නේ නැති වෙන්න ලූප් එකක් ඇතුළේ දුවන්නේ)
    logging.info("Lanka AI Bot is starting via Polling...")
    while True:
        try:
            bot.polling(none_stop=True, timeout=60, long_polling_timeout=60)
        except Exception as e:
            logging.error(f"Bot crashed, restarting in 5 seconds... Error: {e}")
            time.sleep(5)
