# retoor <retoor@molodetz.nl>

import logging
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from devplacepy.database import (
    get_leaderboard,
    get_user_rank,
    get_site_stats,
    get_top_authors,
    get_featured_news,
)
from devplacepy.utils import get_current_user
from devplacepy.seo import list_page_seo
from devplacepy.responses import respond
from devplacepy.schemas import LeaderboardOut

logger = logging.getLogger(__name__)
router = APIRouter()

TOP_LIMIT = 50


@router.get("", response_class=HTMLResponse)
async def leaderboard_page(request: Request):
    entries = get_leaderboard(TOP_LIMIT, 0)

    user = get_current_user(request)
    user_rank = get_user_rank(user["uid"]) if user else None

    stats = get_site_stats()
    top_authors = get_top_authors(5)
    featured_news = get_featured_news(5)

    seo_ctx = list_page_seo(
        request,
        title="Leaderboard",
        description="Top contributors on DevPlace ranked by the stars their posts, projects, and gists have earned.",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Leaderboard", "url": "/leaderboard"},
        ],
    )
    return respond(
        request,
        "leaderboard.html",
        {
            **seo_ctx,
            "request": request,
            "user": user,
            "entries": entries,
            "user_rank": user_rank,
            "total_members": stats["total_members"],
            "posts_today": stats["posts_today"],
            "total_projects": stats["total_projects"],
            "total_gists": stats["total_gists"],
            "top_authors": top_authors,
            "featured_news": featured_news,
        },
        model=LeaderboardOut,
    )
