"""cortex/api/routes/context.py — Context window usage endpoint (Issue #329)."""

from __future__ import annotations

import logging
from typing import Any, Dict, List, Optional

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

from cortex.api.deps import PREFIX, get_plugin

logger = logging.getLogger(__name__)

router = APIRouter()


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

    @router.get(
        f"{PREFIX}/context/usage",
        summary="Current context window token usage",
        tags=["context"],
        operation_id="context_usage",
    )
    async def get_context_usage(
        total_context: Optional[int] = None,
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> JSONResponse:
        """Return the current context window token usage breakdown.

        Query parameters:
            total_context: Optional context window size override (tokens).
                           If omitted, uses the calculator's last allocated size
                           (or 0 if allocate() has not been called).

        Returns a ContextUsageReport as JSON with per-category breakdown.
        """
        calculator = getattr(plugin, "context_calculator", None)
        if calculator is None:
            # Calculator not wired into the plugin — return a minimal response
            return JSONResponse(
                status_code=200,
                content={
                    "total_budget": 0,
                    "total_used": 0,
                    "total_remaining": 0,
                    "utilization": 0.0,
                    "by_category": {},
                    "warnings": [],
                    "note": "context_calculator not initialised on this plugin instance",
                },
            )

        # Optionally re-run allocation if a context size was provided
        if total_context is not None and total_context > 0:
            calculator.allocate(total_context)

        report = calculator.get_usage()

        by_category_out: Dict[str, Any] = {}
        for cat, cu in report.by_category.items():
            by_category_out[cat] = {
                "budget": cu.budget,
                "used": cu.used,
                "remaining": cu.remaining,
                "item_count": cu.item_count,
                "utilization": round(cu.utilization, 4),
            }

        return JSONResponse(
            status_code=200,
            content={
                "total_budget": report.total_budget,
                "total_used": report.total_used,
                "total_remaining": report.total_remaining,
                "utilization": round(report.utilization, 4),
                "by_category": by_category_out,
                "warnings": list(report.warnings),
            },
        )
