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

import structlog
from fastapi import APIRouter, Header, Request
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()


def get_cost_ledger():
    return get_router().ledger


def _extract_api_key(auth_header: str | None) -> str | None:
    """Extract API key from Authorization header."""
    if not auth_header:
        return None
    # Handle "Bearer <key>" format
    if auth_header.lower().startswith("bearer "):
        return auth_header[7:].strip()
    return auth_header.strip()


def _resolve_vm_from_key(api_key: str | None) -> dict[str, str] | None:
    """Resolve API key to VM info if it's a VM key."""
    if not api_key or not api_key.startswith("vm-key-"):
        return None
    # Try to load from vm_key_mappings.json
    import json
    from pathlib import Path
    mapping_path = Path.home() / ".config/proxym/vms/vm_key_mappings.json"
    if mapping_path.exists():
        try:
            mappings = json.loads(mapping_path.read_text())
            if api_key in mappings:
                return {
                    "vm_id": mappings[api_key].get("vm_id", "unknown"),
                    "account_id": mappings[api_key].get("account_id", ""),
                    "tool": mappings[api_key].get("tool", ""),
                }
        except Exception:
            pass
    return None


@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(
    request: Request,
    authorization: str | None = Header(None, alias="Authorization"),
    x_api_key: str | None = Header(None, alias="X-Api-Key"),
):
    """Health check with optional VM identification.

    When called from a VM with proper API key, returns VM identification info.
    """
    # Try to identify calling VM
    api_key = _extract_api_key(authorization) or x_api_key
    vm_info = _resolve_vm_from_key(api_key)

    response: dict = {
        "status": "ok",
        "version": "0.1.0",
        "proxy_url": str(request.base_url).rstrip("/"),
    }

    if vm_info:
        response["vm"] = vm_info
        response["message"] = f"Hello {vm_info['vm_id']}, proxym is ready"
    else:
        response["message"] = "proxym is ready"

    return response


@router.get("/v1/models")
async def list_models():
    """List available models (OpenAI-compatible) including model aliases."""
    models_list = []
    settings = get_settings()
    providers = set(settings.available_providers().keys())

    # Add actual models
    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."""
    ledger = get_cost_ledger()
    return {
        "daily_remaining_usd": round(ledger.daily_remaining, 4),
        "monthly_remaining_usd": round(ledger.monthly_remaining, 4),
        "daily_limit_usd": ledger.daily_limit,
        "monthly_limit_usd": ledger.monthly_limit,
    }


## /v1/context/stats is served by context_api.py router
