# /opt/docker/dev/service_finder/backend/app/api/v1/endpoints/gamification.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, desc
from typing import List

from app.db.session import get_db
from app.api.deps import get_current_user
from app.models.identity import User
from app.models.gamification import UserStats, PointsLedger
from app.services.config_service import config

router = APIRouter()

@router.get("/my-stats")
async def get_my_stats(db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user)):
    """A bejelentkezett felhasználó aktuális XP-je, szintje és büntetőpontjai."""
    stmt = select(UserStats).where(UserStats.user_id == current_user.id)
    stats = (await db.execute(stmt)).scalar_one_or_none()
    
    if not stats:
        return {"total_xp": 0, "current_level": 1, "penalty_points": 0}
    
    return stats

@router.get("/leaderboard")
async def get_leaderboard(limit: int = 10, db: AsyncSession = Depends(get_db)):
    """A 10 legtöbb XP-vel rendelkező felhasználó listája."""
    stmt = (
        select(User.email, UserStats.total_xp, UserStats.current_level)
        .join(UserStats, User.id == UserStats.user_id)
        .order_by(desc(UserStats.total_xp))
        .limit(limit)
    )
    result = await db.execute(stmt)
    # Az email-eket maszkoljuk a GDPR miatt (pl. k***s@p***.hu)
    return [
        {"user": f"{r[0][:2]}***@{r[0].split('@')[1]}", "xp": r[1], "level": r[2]} 
        for r in result.all()
    ]