import os
import json
import time
import asyncio
import html
import threading
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.constants import ParseMode
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, ContextTypes, filters

from database import db
from surface_api import surface_api
from utils import (main_menu_keyboard, get_display_number, user_services_kb, user_countries_kb, 
                   user_ranges_kb, admin_keyboard, admin_services_kb, admin_countries_kb, admin_ranges_kb)
from config import BOT_TOKEN, ADMIN_IDS

# ============================================================
# BACKGROUND ASYNCIO LOOP (FOR CPANEL WSGI)
# ============================================================
_bg_loop = asyncio.new_event_loop()

def start_bg_loop(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()

# Start the event loop in a daemon thread so it survives across requests
threading.Thread(target=start_bg_loop, args=(_bg_loop,), daemon=True).start()

# ============================================================
# BOT LOGIC & HANDLERS
# ============================================================
global_otp_queue = {}
USER_STATES = {}

bot_application = Application.builder().token(BOT_TOKEN).updater(None).build()

async def start_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user = update.effective_user
    if not db.get_user(user.id):
        db.save_user(user.id, {"user_id": user.id, "username": user.username, "balance": 0.0, "total_otp_count": 0})
    USER_STATES.pop(user.id, None)
    await update.message.reply_text("স্বাগতম! নিচের মেনু থেকে অপশন সিলেক্ট করুন:", reply_markup=main_menu_keyboard(user.id))

async def handle_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    text = update.message.text
    
    if text == "📱 Get Number":
        services = db.get_services()
        kb = user_services_kb(services) if services else InlineKeyboardMarkup([[InlineKeyboardButton("No Services", callback_data="none")]])
        await update.message.reply_text("📌 <b>সার্ভিস সিলেক্ট করুন:</b>", reply_markup=kb, parse_mode=ParseMode.HTML)
        USER_STATES.pop(user_id, None)
        return
        
    elif text == "💳 Wallet":
        user = db.get_user(user_id)
        bal = user.get("balance", 0.0)
        await update.message.reply_text(f"💳 <b>My Wallet</b>\n\n💰 বর্তমান ব্যালেন্স: <code>{bal:.2f} ৳</code>", parse_mode=ParseMode.HTML)
        USER_STATES.pop(user_id, None)
        return
        
    elif text == "🏆 Leaderboard":
        otp_rate = float(db.get_setting("otp_rate", 2.0))
        all_users = db.get_all_users()
        top_users = sorted(all_users.values(), key=lambda x: x.get("total_otp_count", 0), reverse=True)[:5]
        
        txt = "🏆 <b>Top Earners Leaderboard</b>\n━━━━━━━━━━━━━━━━━━\n"
        emojis = ["🥇", "🥈", "🥉", "4️⃣", "5️⃣"]
        has_data = False
        for idx, u in enumerate(top_users):
            if u.get("total_otp_count", 0) > 0:
                has_data = True
                name = html.escape(u.get("username") or f"User {u.get('user_id')}")
                txt += f"{emojis[idx]} <b>{name}</b> — <code>{u['total_otp_count']}</code> OTPs | <code>{u['total_otp_count']*otp_rate:.2f} ৳</code>\n"
        if not has_data: txt += "এখনো কোনো ডেটা নেই।"
        await update.message.reply_text(txt, parse_mode=ParseMode.HTML)
        USER_STATES.pop(user_id, None)
        return
        
    elif text == "🚦 Traffic":
        msg = await update.message.reply_text("⏳ ট্রাফিক ডেটা লোড হচ্ছে...")
        t_data = await surface_api.get_live_traffic()
        if t_data.get("success"):
            services = t_data["data"].get("services", [])
            if not services:
                await msg.edit_text("🚦 <b>Live Traffic</b>\n\nবর্তমানে কোনো অ্যাক্টিভ সার্ভিস নেই।", parse_mode=ParseMode.HTML)
            else:
                txt = "🚦 <b>Live Traffic (Hot Ranges)</b>\n━━━━━━━━━━━━━━━━━━\n"
                for srv in services:
                    txt += f"📌 <b>Service:</b> {srv.get('sid')}\n🔥 Hits: <code>{srv.get('hit_count', 0)}</code>\n🔢 Hot Ranges: <code>{', '.join(srv.get('ranges', []))}</code>\n\n"
                await msg.edit_text(txt, parse_mode=ParseMode.HTML)
        else:
            await msg.edit_text("❌ ট্রাফিক ডেটা ফেচ করতে সমস্যা হয়েছে।")
        USER_STATES.pop(user_id, None)
        return
        
    elif text == "⚙️ Admin Panel" and user_id in ADMIN_IDS:
        await update.message.reply_text("👑 <b>Admin Panel</b>", reply_markup=admin_keyboard(), parse_mode=ParseMode.HTML)
        USER_STATES.pop(user_id, None)
        return

    # Admin Settings Logic 
    state = USER_STATES.get(user_id)
    if state:
        action = state['action']
        if text.lower() == 'cancel':
            USER_STATES.pop(user_id, None)
            await update.message.reply_text("❌ বাতিল করা হয়েছে।")
            return

        if action == "admin_timeout" and user_id in ADMIN_IDS:
            if text.isdigit():
                db.set_setting("otp_timeout", int(text))
                await update.message.reply_text("✅ Timeout আপডেট করা হয়েছে!", reply_markup=admin_keyboard())
        elif action == "admin_api" and user_id in ADMIN_IDS:
            db.set_setting("surface_api_key", text.strip())
            await update.message.reply_text("✅ API Key সেভ করা হয়েছে!", reply_markup=admin_keyboard())
        elif action == "admin_url" and user_id in ADMIN_IDS:
            db.set_setting("surface_base_url", text.strip())
            await update.message.reply_text("✅ Base URL সেভ করা হয়েছে!", reply_markup=admin_keyboard())
        elif action == "admin_rate" and user_id in ADMIN_IDS:
            try:
                db.set_setting("otp_rate", float(text))
                await update.message.reply_text("✅ OTP Rate আপডেট করা হয়েছে!", reply_markup=admin_keyboard())
            except: pass
        elif action == "add_srv" and user_id in ADMIN_IDS:
            db.add_service(text.strip().lower())
            await update.message.reply_text("✅ সার্ভিস এড করা হয়েছে!", reply_markup=admin_services_kb(db.get_services()))
        elif action == "rem_srv" and user_id in ADMIN_IDS:
            db.remove_service(text.strip().lower())
            await update.message.reply_text("✅ সার্ভিস রিমুভ করা হয়েছে!", reply_markup=admin_services_kb(db.get_services()))
        elif action == "add_cntr" and user_id in ADMIN_IDS:
            srv = state['service']
            db.add_country(srv, text.strip().lower())
            await update.message.reply_text("✅ কান্ট্রি এড করা হয়েছে!", reply_markup=admin_countries_kb(srv, db.get_countries(srv)))
        elif action == "rem_cntr" and user_id in ADMIN_IDS:
            srv = state['service']
            db.remove_country(srv, text.strip().lower())
            await update.message.reply_text("✅ কান্ট্রি রিমুভ করা হয়েছে!", reply_markup=admin_countries_kb(srv, db.get_countries(srv)))
        elif action == "add_rng" and user_id in ADMIN_IDS:
            srv = state['service']
            cntr = state['country']
            db.add_range(srv, cntr, text.strip())
            await update.message.reply_text("✅ রেঞ্জ এড করা হয়েছে!", reply_markup=admin_ranges_kb(srv, cntr, db.get_ranges(srv, cntr)))
            
        USER_STATES.pop(user_id, None)

async def handle_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    data = query.data
    user_id = query.from_user.id
    
    if data == "user_get_number":
        services = db.get_services()
        kb = user_services_kb(services) if services else InlineKeyboardMarkup([[InlineKeyboardButton("No Services", callback_data="none")]])
        await query.edit_message_text("📌 <b>সার্ভিস সিলেক্ট করুন:</b>", reply_markup=kb, parse_mode=ParseMode.HTML)
        
    elif data.startswith("usr_srv_"):
        service = data.replace("usr_srv_", "")
        countries = db.get_countries(service)
        await query.edit_message_text(f"🌐 <b>সার্ভিস: {service.title()}</b>\nকান্ট্রি সিলেক্ট করুন:", reply_markup=user_countries_kb(service, countries), parse_mode=ParseMode.HTML)
        
    elif data.startswith("usr_cntr_"):
        parts = data.replace("usr_cntr_", "").split(":")
        service, country = parts[0], parts[1]
        ranges = db.get_ranges(service, country)
        await query.edit_message_text(f"🌐 সার্ভিস: {service.title()}\n🌍 কান্ট্রি: {country.title()}\n\n🔢 <b>রেঞ্জ সিলেক্ট করুন:</b>", reply_markup=user_ranges_kb(service, country, ranges), parse_mode=ParseMode.HTML)
        
    elif data.startswith("usr_ext_"):
        parts = data.replace("usr_ext_", "").split(":")
        service, country, prefix = parts[0], parts[1], parts[2]
        await query.edit_message_text("⏳ নাম্বার বের করা হচ্ছে...")
        res = await surface_api.get_number(service=service, country=country, prefix=prefix)
        
        if res.get("success"):
            num_id = res["number_id"]
            full_num = res["number"]
            display_num = get_display_number(full_num)
            task_data = {
                "chat_id": user_id, "num_id": num_id, "full_number": full_num,
                "display_number": display_num, "added_time": time.time(), "received_otps": []
            }
            global_otp_queue[num_id] = task_data
            db.save_active_task(num_id, task_data)
            
            timeout = db.get_setting("otp_timeout", 20)
            text = f"✅ <b>নাম্বার পাওয়া গেছে!</b>\n\n📌 সার্ভিস: {service.title()}\n🌍 দেশ: {country.title()}\n📱 নাম্বার: <code>{display_num}</code>\n\n<i>এই নাম্বারে ওটিপি এলে আপনাকে অটোমেটিক মেসেজ দেওয়া হবে। সময়: {timeout} মিনিট।</i>"
            kb = InlineKeyboardMarkup([[InlineKeyboardButton("🔙 Back to Country", callback_data=f"usr_srv_{service}")]])
            await query.edit_message_text(text, reply_markup=kb, parse_mode=ParseMode.HTML)
        else:
            kb = InlineKeyboardMarkup([[InlineKeyboardButton("🔄 Try Again", callback_data=f"usr_cntr_{service}:{country}")]])
            await query.edit_message_text(f"❌ {res.get('message')}", reply_markup=kb)

    # Admin Callbacks
    elif data == "admin_main" and user_id in ADMIN_IDS:
        USER_STATES.pop(user_id, None)
        await query.edit_message_text("👑 <b>Admin Panel</b>", reply_markup=admin_keyboard(), parse_mode=ParseMode.HTML)
    elif data == "admin_toggle_cc" and user_id in ADMIN_IDS:
        current = db.get_setting("include_cc", "ON")
        db.set_setting("include_cc", "OFF" if current == "ON" else "ON")
        await query.edit_message_reply_markup(admin_keyboard())
    elif data == "close_panel":
        await query.message.delete()
        USER_STATES.pop(user_id, None)
        
    elif data == "admin_timeout" and user_id in ADMIN_IDS:
        USER_STATES[user_id] = {"action": "admin_timeout"}
        await query.edit_message_text("বর্তমান Timeout (মিনিটে) লিখে পাঠান (Cancel লিখতে cancel করুন):")
    elif data == "admin_set_api" and user_id in ADMIN_IDS:
        USER_STATES[user_id] = {"action": "admin_api"}
        await query.edit_message_text("আপনার Surface API Key লিখে পাঠান:")
    elif data == "admin_set_url" and user_id in ADMIN_IDS:
        USER_STATES[user_id] = {"action": "admin_url"}
        await query.edit_message_text("Base URL লিখে পাঠান:")
    elif data == "admin_otp_rate" and user_id in ADMIN_IDS:
        USER_STATES[user_id] = {"action": "admin_rate"}
        await query.edit_message_text("নতুন রেট লিখে পাঠান (যেমন: 2.5):")
        
    elif data == "admin_manage_services" and user_id in ADMIN_IDS:
        services = db.get_services()
        await query.edit_message_text("🛠 <b>Manage Services</b>", reply_markup=admin_services_kb(services), parse_mode=ParseMode.HTML)
    elif data == "add_srv" and user_id in ADMIN_IDS:
        USER_STATES[user_id] = {"action": "add_srv"}
        await query.edit_message_text("নতুন সার্ভিসের নাম লিখুন:")
    elif data == "rem_srv" and user_id in ADMIN_IDS:
        USER_STATES[user_id] = {"action": "rem_srv"}
        await query.edit_message_text("রিমুভ করতে সার্ভিসের নাম লিখুন:")
        
    elif data.startswith("mng_srv_") and user_id in ADMIN_IDS:
        service = data.replace("mng_srv_", "")
        countries = db.get_countries(service)
        await query.edit_message_text(f"🌐 <b>Countries for {service.title()}</b>", reply_markup=admin_countries_kb(service, countries), parse_mode=ParseMode.HTML)
    elif data.startswith("add_cntr_") and user_id in ADMIN_IDS:
        service = data.replace("add_cntr_", "")
        USER_STATES[user_id] = {"action": "add_cntr", "service": service}
        await query.edit_message_text(f"{service.title()} এর জন্য নতুন কান্ট্রির নাম লিখুন:")
    elif data.startswith("rem_cntr_") and user_id in ADMIN_IDS:
        service = data.replace("rem_cntr_", "")
        USER_STATES[user_id] = {"action": "rem_cntr", "service": service}
        await query.edit_message_text(f"{service.title()} থেকে রিমুভ করতে কান্ট্রির নাম লিখুন:")
        
    elif data.startswith("mng_cntr_") and user_id in ADMIN_IDS:
        parts = data.replace("mng_cntr_", "").split(":")
        service, country = parts[0], parts[1]
        ranges = db.get_ranges(service, country)
        await query.edit_message_text(f"🔢 <b>Ranges for {country.title()} ({service.title()})</b>", reply_markup=admin_ranges_kb(service, country, ranges), parse_mode=ParseMode.HTML)
    elif data.startswith("add_rng_") and user_id in ADMIN_IDS:
        parts = data.replace("add_rng_", "").split(":")
        service, country = parts[0], parts[1]
        USER_STATES[user_id] = {"action": "add_rng", "service": service, "country": country}
        await query.edit_message_text("নতুন রেঞ্জ লিখুন (যেমন: 017):")
    elif data.startswith("rem_rng_") and user_id in ADMIN_IDS:
        parts = data.replace("rem_rng_", "").split(":")
        service, country, range_val = parts[0], parts[1], parts[2]
        db.remove_range(service, country, range_val)
        await query.edit_message_reply_markup(admin_ranges_kb(service, country, db.get_ranges(service, country)))

bot_application.add_handler(CommandHandler("start", start_cmd))
bot_application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_text))
bot_application.add_handler(CallbackQueryHandler(handle_callback))

# ============================================================
# OTP WORKER (Runs inside _bg_loop safely)
# ============================================================
async def otp_worker():
    while True:
        if global_otp_queue:
            current_time = time.time()
            timeout_mins = int(db.get_setting("otp_timeout", 20))
            timeout_secs = timeout_mins * 60
            
            active_ids = []
            expired_ids = []
            for num_id, task in list(global_otp_queue.items()):
                if current_time - task['added_time'] > timeout_secs:
                    expired_ids.append(num_id)
                else:
                    active_ids.append(num_id)
                    
            for num_id in expired_ids:
                task = global_otp_queue.pop(num_id, None)
                db.delete_active_task(num_id)
                if task:
                    try:
                        await bot_application.bot.send_message(
                            chat_id=task['chat_id'],
                            text=f"⏳ <b>Session Expired!</b>\nনাম্বার: <code>{task['display_number']}</code>\n{timeout_mins} মিনিট পার হয়ে যাওয়ায় নাম্বারটি বাতিল করা হয়েছে।",
                            parse_mode=ParseMode.HTML
                        )
                    except: pass
                    
            if active_ids:
                results = await surface_api.get_batch_otps(active_ids)
                for num_id, res in results.items():
                    if res.get("success") and num_id in global_otp_queue:
                        task = global_otp_queue[num_id]
                        new_otps = res.get("otps", [])
                        for otp_data in new_otps:
                            code = otp_data["code"]
                            if code not in task["received_otps"]:
                                task["received_otps"].append(code)
                                rate = float(db.get_setting("otp_rate", 2.0))
                                db.add_balance(task['chat_id'], rate)
                                user = db.get_user(task['chat_id'])
                                user["total_otp_count"] = user.get("total_otp_count", 0) + 1
                                db.save_user(task['chat_id'], user)
                                msg = f"🎉 <b>New OTP Received!</b>\n\n📱 নাম্বার: <code>{task['display_number']}</code>\n🔑 কোড: <code>{code}</code>\n💬 SMS: <pre>{html.escape(otp_data['sms'])}</pre>\n💰 আয়: <code>+{rate} ৳</code>"
                                try:
                                    await bot_application.bot.send_message(chat_id=task['chat_id'], text=msg, parse_mode=ParseMode.HTML)
                                except: pass
                        db.save_active_task(num_id, task)
        await asyncio.sleep(5)

# ============================================================
# INITIALIZATION & WSGI HANDLER
# ============================================================
_initialized = False

async def initialize_bot():
    global _initialized
    if _initialized: return
    await bot_application.initialize()
    await bot_application.start()
    
    tasks = db.get_active_tasks()
    current_time = time.time()
    timeout_secs = int(db.get_setting("otp_timeout", 20)) * 60
    for num_id, task in tasks.items():
        if current_time - task['added_time'] < timeout_secs:
            global_otp_queue[num_id] = task
            
    # Start the worker loop safely
    asyncio.create_task(otp_worker())
    _initialized = True

async def process_webhook_data(body):
    try:
        update_data = json.loads(body.decode("utf-8"))
        await initialize_bot()
        update = Update.de_json(update_data, bot_application.bot)
        await bot_application.process_update(update)
        return "200 OK", [("Content-Type", "application/json")], b'{"ok":true}'
    except Exception as e:
        print(f"Error: {e}")
        return "500 Internal Server Error", [("Content-Type", "application/json")], b'{"ok":false}'

def application(environ, start_response):
    path = environ.get("PATH_INFO", "/")
    
    if path == "/webhook":
        content_length = int(environ.get("CONTENT_LENGTH", "0"))
        body = environ["wsgi.input"].read(content_length) if content_length > 0 else b"{}"
        
        # WSGI Thread Safe Execution
        future = asyncio.run_coroutine_threadsafe(process_webhook_data(body), _bg_loop)
        status, headers, response_body = future.result()
        
        start_response(status, headers)
        return [response_body]
        
    elif path == "/ping":
        start_response("200 OK", [("Content-Type", "text/plain")])
        return [b"pong"]
        
    start_response("200 OK", [("Content-Type", "text/plain")])
    return [b"Bot WSGI is running. Set Telegram webhook to /webhook path."]
