import json
from config import OUTPUT_FILE
from bot_handlers import send_message, create_keyboard, user_search_results


def search_in_question(question: dict, keyword: str) -> list:
    """جستجو در سوال"""
    found_in = []
    keyword_lower = keyword.lower()
    
    if keyword_lower in question.get('question', '').lower():
        found_in.append("📝 متن سوال")
    
    if question.get('options'):
        for option_key, option_value in question['options'].items():
            if keyword_lower in option_value.lower():
                found_in.append(f"📋 {option_key}")
                break
    
    correct_answer = question.get('correct_answer', '')
    if correct_answer and keyword_lower in correct_answer.lower():
        found_in.append("✅ جواب درست")
    
    return found_in


def highlight_text(text: str, keyword: str) -> str:
    """هایلایت کردن کلمه جستجو شده"""
    if not text:
        return text
    
    keyword_lower = keyword.lower()
    text_lower = text.lower()
    
    result = []
    last_idx = 0
    
    while True:
        idx = text_lower.find(keyword_lower, last_idx)
        if idx == -1:
            result.append(text[last_idx:])
            break
        result.append(text[last_idx:idx])
        result.append(f"**{text[idx:idx + len(keyword)]}**")
        last_idx = idx + len(keyword)
    
    return "".join(result)


async def advanced_search(chat_id: int, keyword: str):
    """جستجوی پیشرفته"""
    try:
        with open(OUTPUT_FILE, "r", encoding="utf-8") as f:
            questions = json.load(f)
        
        search_results = []
        for q in questions:
            found_locations = search_in_question(q, keyword)
            if found_locations:
                q_copy = q.copy()
                q_copy['found_in'] = found_locations
                search_results.append(q_copy)
        
        if not search_results:
            await send_message(chat_id, f"❌ هیچ نتیجه‌ای برای '{keyword}' پیدا نشد!")
            return
        
        user_search_results[chat_id] = {
            "results": search_results,
            "keyword": keyword,
            "current_page": 0
        }
        
        await show_search_results_page(chat_id, 0)
        
    except FileNotFoundError:
        await send_message(chat_id, "❌ هنوز هیچ سوالی ذخیره نشده!")


async def show_search_results_page(chat_id: int, page: int):
    """نمایش صفحه نتایج جستجو"""
    from config import ITEMS_PER_PAGE
    
    search_data = user_search_results.get(chat_id)
    if not search_data:
        await send_message(chat_id, "❌ نتایج منقضی شده.")
        return
    
    results = search_data["results"]
    keyword = search_data["keyword"]
    total_pages = (len(results) + ITEMS_PER_PAGE - 1) // ITEMS_PER_PAGE
    
    start_idx = page * ITEMS_PER_PAGE
    end_idx = min(start_idx + ITEMS_PER_PAGE, len(results))
    page_results = results[start_idx:end_idx]
    
    search_data["current_page"] = page
    
    result_text = f"🔍 **نتایج جستجو: '{keyword}'**\n"
    result_text += f"📊 {len(results)} سوال | صفحه {page + 1}/{total_pages}\n"
    result_text += "━" * 30 + "\n\n"
    
    for i, q in enumerate(page_results, start_idx + 1):
        preview = highlight_text(q['question'][:80], keyword)
        if len(q['question']) > 80:
            preview += "..."
        
        has_img = " 📸" if q.get('has_images') else ""
        result_text += f"{i}. 📋 [ID: {q['id']}]{has_img}\n   📝 {preview}\n"
        result_text += f"   🔍 {', '.join(q['found_in'])}\n\n"
    
    buttons = []
    for i, q in enumerate(page_results, start_idx + 1):
        buttons.append([(f"📋 مشاهده سوال {q['id']}", f"show_question_{q['id']}")])
    
    nav_buttons = []
    if page > 0:
        nav_buttons.append(("⬅️ صفحه قبل", f"page_{page - 1}_search"))
    if page < total_pages - 1:
        nav_buttons.append(("صفحه بعد ➡️", f"page_{page + 1}_search"))
    
    if nav_buttons:
        buttons.append(nav_buttons)
    
    buttons.append([
        ("🔍 جستجوی جدید", "advanced_search"),
        ("🔙 منوی اصلی", "back_to_menu")
    ])
    
    await send_message(chat_id, result_text, reply_markup=create_keyboard(buttons))