import json
import os
import aiohttp
from config import BASE_API_URL

# دیکشنری‌های نگهداری state کاربران
user_states = {}
user_sessions = {}
user_search_results = {}
user_view_data = {}

# 🆕 یه session مشترک برای همه
_http_session = None


async def get_session() -> aiohttp.ClientSession:
    """دریافت session مشترک (می‌سازه اگه وجود نداشته باشه)"""
    global _http_session
    if _http_session is None or _http_session.closed:
        _http_session = aiohttp.ClientSession()
    return _http_session


async def close_session():
    """بستن session"""
    global _http_session
    if _http_session and not _http_session.closed:
        await _http_session.close()
        _http_session = None


async def get_updates(offset: int = None, timeout: int = 30):
    """دریافت آپدیت‌ها با long polling"""
    url = f"{BASE_API_URL}/getUpdates"
    params = {"timeout": timeout}
    if offset:
        params["offset"] = offset
    
    session = await get_session()
    try:
        async with session.get(url, params=params, timeout=aiohttp.ClientTimeout(total=timeout + 10)) as resp:
            data = await resp.json()
            if data.get("ok"):
                return data.get("result", [])
            return []
    except Exception as e:
        print(f"خطا در دریافت آپدیت: {e}")
        return []


async def send_message(chat_id: int, text: str, reply_markup=None):
    """ارسال پیام به کاربر"""
    url = f"{BASE_API_URL}/sendMessage"
    payload = {"chat_id": chat_id, "text": text}
    if reply_markup:
        payload["reply_markup"] = json.dumps(reply_markup)
    
    session = await get_session()
    try:
        async with session.post(url, json=payload, timeout=aiohttp.ClientTimeout(total=10)) as resp:
            return await resp.json()
    except Exception as e:
        print(f"خطا در ارسال پیام: {e}")
        return None


async def send_photo(chat_id: int, photo_path: str, caption: str = ""):
    """ارسال عکس به کاربر"""
    url = f"{BASE_API_URL}/sendPhoto"
    
    try:
        with open(photo_path, "rb") as photo_file:
            form_data = aiohttp.FormData()
            form_data.add_field("chat_id", str(chat_id))
            form_data.add_field("photo", photo_file, filename=os.path.basename(photo_path))
            if caption:
                form_data.add_field("caption", caption)
            
            session = await get_session()
            async with session.post(url, data=form_data) as resp:
                return await resp.json()
    except Exception as e:
        print(f"خطا در ارسال عکس: {e}")
        return None


def create_keyboard(buttons: list):
    """ساخت صفحه کلید inline"""
    keyboard = []
    for row in buttons:
        keyboard_row = []
        for btn_text, btn_data in row:
            keyboard_row.append({"text": btn_text, "callback_data": btn_data})
        keyboard.append(keyboard_row)
    return {"inline_keyboard": keyboard}


async def handle_start(chat_id: int):
    """هندل کردن دستور /start"""
    user_states.pop(chat_id, None)
    user_search_results.pop(chat_id, None)
    user_view_data.pop(chat_id, None)
    
    keyboard = create_keyboard([
        [("🔄 شروع استخراج سوالات", "start_extract")],
        [("👁️ دیدن سوالات", "view_questions")],
        [("🔍 جستجوی پیشرفته", "advanced_search")],
        [("🤖 آپدیت خودکار", "auto_update")],
        [("📋 مشاهده آمار", "show_stats")],
        [("📤 ارسال فایل JSON", "send_json")],
        [("🗑️ حذف دیتابیس", "delete_database")]
    ])
    
    welcome_text = """
👋 **به ربات استخراج سوالات خوش آمدید!**

🎯 قابلیت‌ها:
• استخراج سوالات تستی و تشریحی
• تشخیص و دانلود خودکار عکس‌ها
• جستجوی پیشرفته با گزینه‌های شیشه‌ای
• آپدیت خودکار (هر ۲۰ دقیقه)
• حذف کامل دیتابیس

🔹 از منوی زیر گزینه مورد نظر را انتخاب کنید:
    """
    
    await send_message(chat_id, welcome_text, reply_markup=keyboard)


async def handle_callback(chat_id: int, data: str):
    """هندل کردن callback query ها"""
    from view_utils import show_statistics, send_json_file
    from search_utils import advanced_search, show_search_results_page
    from view_utils import view_questions_in_range, show_view_questions_page, show_question_detail
    import json as json_module
    from config import CONFIG_FILE, AUTO_UPDATE_INTERVAL
    
    if data == "start_extract":
        user_states[chat_id] = "waiting_range_start"
        await send_message(chat_id, "🔢 لطفاً **شماره شروع** بازه را وارد کنید:")

    elif data == "view_questions":
        user_states[chat_id] = "waiting_view_start"
        await send_message(chat_id, "🔢 لطفاً **شماره شروع** بازه برای نمایش را وارد کنید:")

    elif data == "advanced_search":
        user_states[chat_id] = "waiting_advanced_search"
        await send_message(chat_id, "🔍 لطفاً **کلمه یا عبارت** مورد نظر را برای جستجو وارد کنید:")

    elif data == "delete_database":
        await delete_database(chat_id)
    
    elif data == "auto_update":
        last_id = 0
        if os.path.exists(CONFIG_FILE):
            try:
                with open(CONFIG_FILE, "r", encoding="utf-8") as f:
                    config_data = json_module.load(f)
                last_id = config_data.get("last_known_id", 0)
            except:
                pass
        
        if last_id > 0:
            await send_message(chat_id, 
                f"🔢 لطفاً **آخرین ID شناخته شده** را وارد کنید:\n\n"
                f"📝 قبلاً: {last_id}\n"
                f"💡 عدد جدید جایگزین می‌شود")
        else:
            await send_message(chat_id, 
                f"🔢 لطفاً **آخرین ID شناخته شده** را وارد کنید:\n\n"
                f"💡 سوالات از این ID به بعد چک می‌شوند")
        
        user_states[chat_id] = "waiting_auto_update_id"
    
    elif data == "show_stats":
        await show_statistics(chat_id)
    
    elif data == "send_json":
        await send_json_file(chat_id)
    
    elif data == "back_to_menu":
        await handle_start(chat_id)
    
    elif data == "back_to_search":
        search_data = user_search_results.get(chat_id)
        if search_data:
            await show_search_results_page(chat_id, search_data["current_page"])
        else:
            await handle_start(chat_id)
    
    elif data == "back_to_view":
        view_data = user_view_data.get(chat_id)
        if view_data:
            await show_view_questions_page(chat_id, view_data["current_page"])
        else:
            await handle_start(chat_id)
  
    elif data.startswith("show_question_"):
        question_id = int(data.replace("show_question_", ""))
        await show_question_detail(chat_id, question_id)
    
    elif data.startswith("page_"):
        parts = data.replace("page_", "").split("_")
        page = int(parts[0])
        source = parts[1] if len(parts) > 1 else "search"
        
        if source == "view":
            await show_view_questions_page(chat_id, page)
        else:
            await show_search_results_page(chat_id, page)

    elif data.startswith("option_info_"):
        session = await get_session()
        answer_url = f"{BASE_API_URL}/answerCallbackQuery"
        try:
            async with session.post(answer_url, json={
                "callback_query_id": callback_id,
                "text": "👆 گزینه انتخاب شد",
                "show_alert": False
            }) as resp:
                pass
        except:
            pass
        return


async def handle_callback_query(chat_id: int, data: str, callback_id: str):
    """پردازش callback query ها"""
    if data == "no_action":
        session = await get_session()
        answer_url = f"{BASE_API_URL}/answerCallbackQuery"
        try:
            async with session.post(answer_url, json={
                "callback_query_id": callback_id,
                "text": "صفحه فعلی"
            }) as resp:
                pass
        except:
            pass
        return
    
    session = await get_session()
    answer_url = f"{BASE_API_URL}/answerCallbackQuery"
    try:
        async with session.post(answer_url, json={
            "callback_query_id": callback_id
        }) as resp:
            pass
    except:
        pass
    
    await handle_callback(chat_id, data)


async def delete_database(chat_id: int):
    """حذف کامل دیتابیس"""
    import shutil
    from config import OUTPUT_FILE, IMAGES_DIR
    
    questions_count = 0
    images_count = 0
    
    if os.path.exists(OUTPUT_FILE):
        try:
            import json as json_module
            with open(OUTPUT_FILE, "r", encoding="utf-8") as f:
                questions = json_module.load(f)
            questions_count = len(questions)
        except:
            pass
    
    if os.path.exists(IMAGES_DIR):
        images_count = len([f for f in os.listdir(IMAGES_DIR) if os.path.isfile(os.path.join(IMAGES_DIR, f))])
    
    warning = f"🗑️ **در حال حذف دیتابیس...**\n\n📁 سوالات: {questions_count}\n🖼️ عکس‌ها: {images_count}"
    await send_message(chat_id, warning)
    
    if os.path.exists(OUTPUT_FILE):
        try:
            os.remove(OUTPUT_FILE)
            print(f"✅ JSON حذف شد")
        except Exception as e:
            print(f"❌ خطا: {e}")
    
    if os.path.exists(IMAGES_DIR):
        try:
            shutil.rmtree(IMAGES_DIR)
            print(f"✅ پوشه عکس‌ها حذف شد")
        except Exception as e:
            print(f"❌ خطا: {e}")
    
    if not os.path.exists(OUTPUT_FILE) and not os.path.exists(IMAGES_DIR):
        await send_message(chat_id, f"✅ **دیتابیس حذف شد!**\n📊 {questions_count} سوال | {images_count} عکس")
    
    await handle_start(chat_id)