"""cortex/api/routes/llm.py — LLM usage tracking endpoint (Issue #419)."""
from __future__ import annotations

import logging
from datetime import datetime, timezone
from typing import Any, List, Optional

from fastapi import APIRouter, Depends, Query

from cortex.api.deps import PREFIX, get_plugin
from cortex.api.models import LlmUsageResponse

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


def _make_routes(verify_api_key):
    @router.get(f"{PREFIX}/llm/usage", response_model=LlmUsageResponse,
                summary="LLM usage breakdown by tier", tags=["llm"])
    async def get_llm_usage(
        since: Optional[str] = Query(default=None,
            description="ISO 8601 timestamp — only include calls after this time"),
        tier: Optional[str] = Query(default=None,
            description="Filter to a single tier: fast | main | reasoning"),
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ) -> LlmUsageResponse:
        """Return LLM call usage broken down by tier and operation type."""
        errors: List[str] = []
        tracker = None
        llm = getattr(plugin, "llm", None)
        if llm is not None:
            tracker = getattr(llm, "_usage_tracker", None)
        if tracker is None:
            try:
                from cortex.llm.usage_tracker import LLMUsageTracker
                owner_id = getattr(getattr(plugin, "config", None), "owner_id", "default")
                tracker = LLMUsageTracker.get(owner_id)
            except Exception as exc:
                errors.append(f"LLM usage tracker unavailable: {exc}")
                return LlmUsageResponse(errors=errors)
        since_dt: Optional[datetime] = None
        if since is not None:
            try:
                # Handle URL encoding: spaces instead of + (common with query params)
                since_normalized = since.replace("Z", "+00:00").replace(" ", "+")
                since_dt = datetime.fromisoformat(since_normalized)
                if since_dt.tzinfo is None:
                    since_dt = since_dt.replace(tzinfo=timezone.utc)
            except ValueError:
                errors.append(f"Invalid since timestamp {since!r} — must be ISO 8601")
                return LlmUsageResponse(errors=errors)
        tier_filter: Optional[str] = None
        if tier is not None:
            if tier not in {"fast", "main", "reasoning"}:
                errors.append(f"Invalid tier {tier!r} — must be one of: fast, main, reasoning")
                return LlmUsageResponse(errors=errors)
            tier_filter = tier
        try:
            summary = tracker.get_summary(since=since_dt, tier_filter=tier_filter)
        except Exception as exc:
            errors.append(f"Failed to retrieve LLM usage: {exc}")
            return LlmUsageResponse(errors=errors)
        return LlmUsageResponse(
            tiers=summary.get("tiers", {}),
            by_operation=summary.get("by_operation", {}),
            total=summary.get("total", {}),
            generated_at=summary.get("generated_at", ""),
            errors=errors,
        )
