"""System endpoints: health, models, budget — extracted from main.py."""

from __future__ import annotations

import structlog
from fastapi import APIRouter
from fastapi.responses import Response

from proxym.config import get_settings
from proxym.providers import MODELS

from proxym.api._state import get_delta_buffer, get_router

logger = structlog.get_logger()

router = APIRouter()


@router.get("/favicon.ico")
async def favicon():
    """Return empty favicon to prevent 401 errors."""
    return Response(content="", media_type="image/x-icon")


@router.get("/health")
async def health():
    return {"status": "ok", "version": "0.1.0"}


@router.get("/v1/models")
async def list_models():
    """List available models (OpenAI-compatible)."""
    models_list = []
    providers = set(get_settings().available_providers().keys())
    for mid, m in MODELS.items():
        if m.provider in providers:
            models_list.append({
                "id": mid,
                "object": "model",
                "owned_by": m.provider,
                "display_name": m.display_name,
                "input_cost_per_1m": m.input_cost,
                "output_cost_per_1m": m.output_cost,
                "context_window": m.context_window,
                "capabilities": [c.value for c in m.capabilities],
                "tier_range": f"{m.min_tier.value}–{m.max_tier.value}",
            })
    return {"object": "list", "data": models_list}


@router.get("/v1/budget")
async def budget_status():
    """Return current budget usage."""
    rtr = get_router()
    return {
        "daily_remaining_usd": round(rtr.ledger.daily_remaining, 4),
        "monthly_remaining_usd": round(rtr.ledger.monthly_remaining, 4),
        "daily_limit_usd": rtr.ledger.daily_limit,
        "monthly_limit_usd": rtr.ledger.monthly_limit,
    }


@router.get("/v1/context/stats")
async def context_stats():
    """Return delta buffer statistics."""
    buf = get_delta_buffer()
    return buf.get_stats()
