"""
Savings metrics API for the kvict Proxy.

Provides the REST endpoints consumed by both the dashboard and the
browser extension badge. Follows the APIRouter pattern from
packages/caae/quantization_api.py.

Endpoints:
    GET /api/v1/savings/summary   -> SavingsSummary
    GET /api/v1/savings/history   -> List[SavingsHistoryEntry]
    GET /api/v1/usage/by-model    -> List[UsageByModel]
    GET /api/v1/badge             -> lightweight badge payload
"""

from __future__ import annotations

from typing import List

from fastapi import APIRouter, Query

from proxy.schemas import SavingsHistoryEntry, SavingsSummary, UsageByModel
from proxy.store import MetricsStore

router = APIRouter(prefix="/api/v1", tags=["savings"])

# Injected at app startup (see app.py lifespan)
_store: MetricsStore | None = None


def set_store(store: MetricsStore) -> None:
    """Inject the metrics store (called during app startup)."""
    global _store
    _store = store


def _get_store() -> MetricsStore:
    if _store is None:
        raise RuntimeError("MetricsStore not initialized")
    return _store


# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------


@router.get("/savings/summary", response_model=SavingsSummary)
async def get_savings_summary() -> SavingsSummary:
    """Get aggregate savings summary.

    Returns total tokens saved, messages gained, dollars saved,
    cache hit rate, and request counts.
    """
    return _get_store().get_savings_summary()


@router.get("/savings/history", response_model=List[SavingsHistoryEntry])
async def get_savings_history(
    days: int = Query(30, ge=1, le=365),
) -> List[SavingsHistoryEntry]:
    """Get daily savings time series.

    Args:
        days: Number of days to look back (1-365).
    """
    return _get_store().get_savings_history(days=days)


@router.get("/usage/by-model", response_model=List[UsageByModel])
async def get_usage_by_model() -> List[UsageByModel]:
    """Get per-model usage breakdown."""
    return _get_store().get_usage_by_model()


@router.get("/badge")
async def get_badge() -> dict:
    """Lightweight endpoint for the browser extension badge.

    Returns a minimal payload polled every ~60 seconds.
    """
    store = _get_store()
    summary = store.get_savings_summary()
    tokens_saved_today = store.get_tokens_saved_today()
    return {
        "tokens_saved_today": tokens_saved_today,
        "messages_gained": summary.messages_gained,
        "dollars_saved": summary.dollars_saved,
        "cache_hit_rate": round(summary.cache_hit_rate, 3),
    }
