"""cortex/api/routes/stats.py — Dashboard + time-series stats endpoints."""

from __future__ import annotations

import logging
from typing import Any, Dict, List

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import JSONResponse

from cortex.api.deps import PREFIX, _serialise, get_plugin
from cortex.api.models import (
    DashboardStatsResponse,
    MemoryTimeSeriesResponse,
    RequestStatsResponse,
)

logger = logging.getLogger(__name__)

router = APIRouter()


def _make_routes(verify_api_key):
    """Register stats routes with the given auth dependency."""

    @router.get(
        f"{PREFIX}/stats/dashboard",
        response_model=DashboardStatsResponse,
        summary="Dashboard overview statistics",
        tags=["stats"],
    )
    async def get_dashboard_stats(
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> DashboardStatsResponse:
        """Return rich aggregate memory statistics for the dashboard."""
        errors: List[str] = []
        storage = getattr(plugin, "storage", None)
        if storage is None:
            return DashboardStatsResponse(errors=["Storage not available"])

        owner_id = getattr(plugin.config, "owner_id", "default")
        try:
            stats = await storage.get_dashboard_stats(owner_id=owner_id)
            return DashboardStatsResponse(**stats)
        except Exception as exc:
            err = f"Dashboard stats failed: {exc}"
            logger.error(err, exc_info=True)
            errors.append(err)
            return DashboardStatsResponse(errors=errors)

    @router.get(
        f"{PREFIX}/stats/requests",
        response_model=RequestStatsResponse,
        summary="Request activity over time",
        tags=["stats"],
    )
    async def get_request_stats(
        time_range: str = "7d",
        granularity: str = "day",
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> RequestStatsResponse:
        """Return time-series request activity from the request_log table."""
        errors: List[str] = []
        storage = getattr(plugin, "storage", None)
        if storage is None:
            return RequestStatsResponse(errors=["Storage not available"])

        if time_range not in ("1d", "7d", "30d"):
            time_range = "7d"
        if granularity not in ("hour", "day"):
            granularity = "day"

        try:
            if not hasattr(storage, "get_request_stats"):
                return RequestStatsResponse(
                    errors=["Request stats not supported"], time_range=time_range, granularity=granularity
                )
            items = await storage.get_request_stats(
                time_range=time_range,
                granularity=granularity,
            )
            return RequestStatsResponse(
                items=items, time_range=time_range, granularity=granularity, errors=errors
            )
        except Exception as exc:
            err = f"Request stats failed: {exc}"
            logger.error(err, exc_info=True)
            errors.append(err)
            return RequestStatsResponse(
                time_range=time_range, granularity=granularity, errors=errors
            )

    @router.get(
        f"{PREFIX}/stats/memories",
        response_model=MemoryTimeSeriesResponse,
        summary="Memory counts over time",
        tags=["stats"],
    )
    async def get_memory_time_series(
        time_range: str = "30d",
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> MemoryTimeSeriesResponse:
        """Return daily memory creation counts from semantic_claim.created_at."""
        errors: List[str] = []
        storage = getattr(plugin, "storage", None)
        if storage is None:
            return MemoryTimeSeriesResponse(errors=["Storage not available"])

        if time_range not in ("1d", "7d", "30d"):
            time_range = "30d"

        try:
            if not hasattr(storage, "get_memory_stats"):
                return MemoryTimeSeriesResponse(
                    errors=["Memory stats not supported"], time_range=time_range
                )
            items = await storage.get_memory_stats(time_range=time_range)
            return MemoryTimeSeriesResponse(items=items, time_range=time_range, errors=errors)
        except Exception as exc:
            err = f"Memory time series failed: {exc}"
            logger.error(err, exc_info=True)
            errors.append(err)
            return MemoryTimeSeriesResponse(time_range=time_range, errors=errors)
