"""HTML routes for analytics views."""

from __future__ import annotations

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse

router = APIRouter(prefix="/analytics", tags=["analytics"])


@router.get("", response_class=HTMLResponse)
async def analytics_overview(request: Request) -> HTMLResponse:
    """Analytics overview page."""
    templates = request.app.state.templates
    repo = request.app.state.repo

    stats = await repo.get_overview_stats()
    models = await repo.get_model_breakdown()
    agents = await repo.get_agent_breakdown()
    daily_usage = await repo.get_daily_usage(days=30)

    for row in daily_usage:
        if row.get("day"):
            row["day"] = row["day"].strftime("%b %d")
        for k, v in row.items():
            if hasattr(v, "as_tuple"):  # Decimal
                row[k] = float(v)

    return templates.TemplateResponse(
        "analytics/overview.html",
        {
            "request": request,
            "page_title": "Analytics",
            "stats": stats,
            "models": models,
            "agents": agents,
            "daily_usage": daily_usage,
        },
    )


@router.get("/models", response_class=HTMLResponse)
async def models_page(request: Request) -> HTMLResponse:
    """Per-model analytics page."""
    templates = request.app.state.templates
    repo = request.app.state.repo

    models = await repo.get_model_breakdown()

    return templates.TemplateResponse(
        "analytics/models.html",
        {
            "request": request,
            "page_title": "Model Usage",
            "models": models,
        },
    )


@router.get("/agents", response_class=HTMLResponse)
async def agents_page(
    request: Request,
    group_by: str = "class",
) -> HTMLResponse:
    """Per-agent analytics page."""
    templates = request.app.state.templates
    repo = request.app.state.repo

    agents = await repo.get_agent_breakdown(group_by=group_by)

    return templates.TemplateResponse(
        "analytics/agents.html",
        {
            "request": request,
            "page_title": "Agent Usage",
            "agents": agents,
            "group_by": group_by,
        },
    )
