# retoor <retoor@molodetz.nl>

import logging
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, JSONResponse
from devplacepy.utils import require_admin
from devplacepy.seo import base_seo_context, site_url, website_schema
from devplacepy.responses import respond
from devplacepy.schemas import GatewayUsageOut
from devplacepy.services.manager import service_manager
from devplacepy.services.openai_gateway.analytics import build_analytics
from devplacepy.services.openai_gateway.usage import pricing_from_cfg

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


@router.get("/ai-usage", response_class=HTMLResponse)
async def admin_ai_usage(request: Request):
    admin = require_admin(request)
    base = site_url(request)
    seo_ctx = base_seo_context(
        request,
        title="AI usage - Admin",
        description="AI gateway token usage, cost, latency, and reliability metrics.",
        robots="noindex,nofollow",
        breadcrumbs=[
            {"name": "Home", "url": "/feed"},
            {"name": "Admin", "url": "/admin"},
            {"name": "AI usage", "url": "/admin/ai-usage"},
        ],
        schemas=[website_schema(base)],
    )
    return respond(
        request,
        "ai_usage.html",
        {
            **seo_ctx,
            "request": request,
            "user": admin,
            "admin_section": "ai-usage",
        },
        model=GatewayUsageOut,
    )


@router.get("/ai-usage/data")
async def admin_ai_usage_json(request: Request, hours: int = 48, top_n: int = 10):
    require_admin(request)
    service = service_manager.get_service("openai")
    pricing = pricing_from_cfg(service.get_config()) if service is not None else None
    return JSONResponse(build_analytics(hours, top_n=top_n, pricing=pricing))
