# retoor <retoor@molodetz.nl>

import logging
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, JSONResponse
from devplacepy.responses import respond
from devplacepy.schemas.statistics import StatisticsOut
from devplacepy.seo import base_seo_context, site_url, website_schema
from devplacepy.services.statistics.build import build_statistics_tab
from devplacepy.services.statistics.common import VALID_TABS
from devplacepy.utils import require_admin

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

TAB_LABELS = (
    ("overview", "Overview", "\U0001f4ca"),
    ("visitors", "Visitors", "\U0001f441\ufe0f"),
    ("members", "Members", "\U0001f465"),
    ("content", "Content", "\U0001f4dd"),
    ("engagement", "Engagement", "\U0001f525"),
    ("social", "Social", "\U0001f91d"),
    ("ai", "AI", "\U0001f916"),
    ("devii", "Devii", "\u2728"),
    ("services", "Services", "\u2699\ufe0f"),
    ("containers", "Containers", "\U0001f4e6"),
    ("game", "Game", "\U0001f3ae"),
    ("awards", "Awards", "\U0001f3c6"),
    ("moderation", "Moderation", "\U0001f6e1\ufe0f"),
    ("tools", "Tools", "\U0001f527"),
    ("storage", "Storage", "\U0001f4be"),
)


@router.get("/statistics", response_class=HTMLResponse)
async def admin_statistics(request: Request, tab: str = "overview", hours: int = 168):
    admin = require_admin(request)
    active = tab if tab in VALID_TABS else "overview"
    base = site_url(request)
    seo_ctx = base_seo_context(
        request,
        title="Statistics - Admin",
        description="Platform statistics with trends, visitors, content, engagement, and operations.",
        robots="noindex,nofollow",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Admin", "url": "/admin"},
            {"name": "Statistics", "url": "/admin/statistics"},
        ],
        schemas=[website_schema(base)],
    )
    initial = build_statistics_tab(active, hours, compare=True, top_n=10)
    tabs = [
        {"key": key, "label": label, "icon": icon, "active": key == active}
        for key, label, icon in TAB_LABELS
    ]
    return respond(
        request,
        "admin_statistics.html",
        {
            **seo_ctx,
            "request": request,
            "user": admin,
            "admin_section": "statistics",
            "tabs": tabs,
            "active_tab": active,
            "window_hours": hours,
            "initial": initial,
        },
        model=StatisticsOut,
    )


@router.get("/statistics/data")
async def admin_statistics_data(
    request: Request,
    tab: str = "overview",
    hours: int = 168,
    compare: int = 1,
    top_n: int = 10,
):
    require_admin(request)
    return JSONResponse(
        build_statistics_tab(
            tab,
            hours,
            compare=bool(compare),
            top_n=top_n,
        )
    )