import json
import os
import asyncio
from config import OUTPUT_FILE, IMAGES_DIR, VIEW_ITEMS_PER_PAGE
from bot_handlers import send_message, send_photo, create_keyboard, user_view_data


async def show_statistics(chat_id: int):
    """نمایش آمار"""
    try:
        with open(OUTPUT_FILE, "r", encoding="utf-8") as f:
            questions = json.load(f)
        
        essay_count = sum(1 for q in questions if q.get('type') == 'essay')
        image_count = sum(1 for q in questions if q.get('has_images'))
        
        ids = [q['id'] for q in questions]
        min_id = min(ids) if ids else 0
        max_id = max(ids) if ids else 0
        
        total_images = len([f for f in os.listdir(IMAGES_DIR) if os.path.isfile(os.path.join(IMAGES_DIR, f))]) if os.path.exists(IMAGES_DIR) else 0
        
        stats = f"""
📊 **آمار:**
📝 کل: {len(questions)} | 📋 تستی: {len(questions) - essay_count} | 📝 تشریحی: {essay_count}
📸 با عکس: {image_count} | 🖼️ عکس‌ها: {total_images}
🔢 محدوده: {min_id} تا {max_id}
📁 حجم: {os.path.getsize(OUTPUT_FILE) / 1024:.1f} KB
        """
        
        await send_message(chat_id, stats, reply_markup=create_keyboard([[("🔙 منوی اصلی", "back_to_menu")]]))
        
    except FileNotFoundError:
        await send_message(chat_id, "❌ هنوز سوالی ذخیره نشده!")


async def send_json_file(chat_id: int):
    """ارسال فایل JSON"""
    try:
        if not os.path.exists(OUTPUT_FILE):
            await send_message(chat_id, "❌ فایل JSON وجود ندارد!")
            return
        
        from config import BASE_API_URL
        import aiohttp
        
        url = f"{BASE_API_URL}/sendDocument"
        with open(OUTPUT_FILE, "rb") as f:
            form_data = aiohttp.FormData()
            form_data.add_field("chat_id", str(chat_id))
            form_data.add_field("document", f, filename=OUTPUT_FILE)
            
            async with aiohttp.ClientSession() as session:
                await session.post(url, data=form_data)
        
        await send_message(chat_id, "✅ فایل ارسال شد!")
    except Exception as e:
        await send_message(chat_id, f"❌ خطا: {str(e)}")


async def send_question_with_images(chat_id: int, question: dict, index: int, total: int):
    """ارسال سوال با عکس‌ها"""
    type_emoji = "📝" if question.get('type') == 'essay' else "📋"
    image_emoji = " 📸" if question.get('has_images') else ""
    
    text = f"{type_emoji} **سوال {index}/{total}**{image_emoji} [ID: {question['id']}]\n"
    text += "━" * 35 + "\n\n"
    text += f"📝 **متن:**\n{question['question']}\n\n"
    
    if question.get('options'):
        text += "📋 **گزینه‌ها:**\n"
        for key, value in question['options'].items():
            if value == question.get('correct_answer'):
                text += f"   ✅ **{key}: {value}**\n"
            else:
                text += f"   ⭕ {key}: {value}\n"
    elif question.get('type') == 'essay':
        text += "📝 **تشریحی**\n"
    
    text += f"\n🔗 {question.get('url', '')}\n"
    
    if question.get('image_urls'):
        text += "\n📸 **لینک عکس‌ها:**\n"
        for idx, img_url in enumerate(question['image_urls'], 1):
            text += f"   {idx}. {img_url}\n"
    
    if question.get('has_images') and question.get('images'):
        await send_message(chat_id, text)
        await asyncio.sleep(0.2)  # 🆕 این خط رو اضافه کن

        
        for img_path in question['images']:
            if os.path.exists(img_path):
                await send_photo(chat_id, img_path, f"📸 عکس سوال [ID: {question['id']}]")
                await asyncio.sleep(0.2)
    else:
        await send_message(chat_id, text)


async def view_questions_in_range(chat_id: int, start: int, end: int):
    """نمایش سوالات بازه"""
    try:
        with open(OUTPUT_FILE, "r", encoding="utf-8") as f:
            all_questions = json.load(f)
        
        range_questions = sorted(
            [q for q in all_questions if start <= q['id'] <= end],
            key=lambda x: x['id']
        )
        
        if not range_questions:
            existing_ids = [q['id'] for q in all_questions]
            msg = f"❌ سوالی در بازه {start}-{end} پیدا نشد!"
            if existing_ids:
                msg += f"\n📋 محدوده موجود: {min(existing_ids)} تا {max(existing_ids)}"
            await send_message(chat_id, msg)
            return
        
        user_view_data[chat_id] = {
            "questions": range_questions,
            "start": start,
            "end": end,
            "current_page": 0
        }
        
        await show_view_questions_page(chat_id, 0)
        
    except FileNotFoundError:
        await send_message(chat_id, "❌ سوالی ذخیره نشده!")


async def show_view_questions_page(chat_id: int, page: int):
    """نمایش صفحه سوالات"""
    view_data = user_view_data.get(chat_id)
    if not view_data:
        await send_message(chat_id, "❌ داده‌ها منقضی شده.")
        return
    
    questions = view_data["questions"]
    start = view_data["start"]
    end = view_data["end"]
    total_pages = (len(questions) + VIEW_ITEMS_PER_PAGE - 1) // VIEW_ITEMS_PER_PAGE
    
    start_idx = page * VIEW_ITEMS_PER_PAGE
    end_idx = min(start_idx + VIEW_ITEMS_PER_PAGE, len(questions))
    page_questions = questions[start_idx:end_idx]
    
    view_data["current_page"] = page
    
    for i, q in enumerate(page_questions, start_idx + 1):
        await send_question_with_images(chat_id, q, i, len(questions))
        
    
    buttons = []
    nav_buttons = []
    if page > 0:
        nav_buttons.append(("⬅️ قبل", f"page_{page - 1}_view"))
    nav_buttons.append((f"📊 {page + 1}/{total_pages}", "no_action"))
    if page < total_pages - 1:
        nav_buttons.append(("بعد ➡️", f"page_{page + 1}_view"))
    buttons.append(nav_buttons)
    
    buttons.append([
        ("🔙 منوی اصلی", "back_to_menu"),
        ("👁️ بازه جدید", "view_questions")
    ])
    
    await send_message(chat_id, f"📄 صفحه {page + 1}/{total_pages} | بازه {start}-{end}", 
                      reply_markup=create_keyboard(buttons))


async def show_question_detail(chat_id: int, question_id: int):
    """نمایش جزئیات یک سوال"""
    try:
        with open(OUTPUT_FILE, "r", encoding="utf-8") as f:
            questions = json.load(f)
        
        question = next((q for q in questions if q["id"] == question_id), None)
        if not question:
            await send_message(chat_id, "❌ سوال پیدا نشد!")
            return
        
        await send_question_with_images(chat_id, question, 1, 1)
        
        await send_message(chat_id, "💡 انتخاب کنید:", reply_markup=create_keyboard([
            [("🔙 نتایج", "back_to_search")],
            [("🔍 جستجوی جدید", "advanced_search")],
            [("🏠 منو", "back_to_menu")]
        ]))
        
    except FileNotFoundError:
        await send_message(chat_id, "❌ سوالی ذخیره نشده!")
        