"""Ranking handlers."""

from aiogram import Router, F
from aiogram.types import CallbackQuery

from services.ranking import get_user_position
from keyboards.user import get_back_to_menu_keyboard

from database import get_top_users

router = Router()


@router.callback_query(F.data == "ranking")
async def show_ranking(callback: CallbackQuery):
    """Show top 20 users in ranking."""
    leaderboard = await get_top_users(limit=50)

    ranking_text = "🏆 رتبه بندی\n\n"
    for idx, user in enumerate(leaderboard, start=1):
        ranking_text += f"{idx}. {user['full_name']} - {user['score']} امتیاز\n"

    # Also show current user position if not in top 20
    from database import get_user_by_telegram_id
    user = await get_user_by_telegram_id(callback.from_user.id)

    if user:
        user_rank = await get_user_position(callback.from_user.id)
        if user_rank.get("rank", 0) > 20:
            ranking_text += f"\n... شما در رتبه {user_rank['rank']} هستید"

    await callback.message.edit_text(ranking_text, reply_markup=get_back_to_menu_keyboard())
    await callback.answer()