"""MCP tools — System status, logs, and models."""
from __future__ import annotations

from typing import Annotated, Any

import structlog
from fastapi import APIRouter, Query

from proxym.mcp._helpers import _get_dashboard

router = APIRouter()
logger = structlog.get_logger()


@router.post("/tools/status")
async def tool_status() -> dict[str, Any]:
    """Full system status: proxy, VMs, accounts, costs."""
    try:
        _vms, _accounts = _get_dashboard()
        return {
            "vms": {"count": len(_vms().list_vms())},
            "accounts": {"count": len(_accounts().list_accounts())},
        }
    except Exception as exc:
        return {"status": "error", "error": str(exc)}


@router.post("/tools/logs")
async def tool_logs(
    lines: Annotated[int, Query(ge=1, le=500)] = 50,
    level: Annotated[str, Query()] = "all",
) -> dict[str, Any]:
    """Recent proxym logs."""
    try:
        from proxym.dashboard import _logs
        return {"logs": _logs(lines=lines, level=level)}
    except Exception as exc:
        return {"logs": [], "error": str(exc)}


@router.post("/tools/models")
async def tool_models() -> dict[str, Any]:
    """List available models with prices."""
    try:
        from proxym.providers import MODELS
        return {
            "models": [
                {
                    "id": m.id,
                    "provider": m.provider,
                    "input_cost": m.input_cost,
                    "output_cost": m.output_cost,
                    "context_window": m.context_window,
                }
                for m in MODELS.values()
            ]
        }
    except Exception as exc:
        return {"models": [], "error": str(exc)}


# ── Schema fragments ─────────────────────────────────────

TOOL_SCHEMA_SYSTEM: list[dict[str, Any]] = [
    {
        "type": "function",
        "function": {
            "name": "status",
            "description": "Full system status: proxy, VMs, accounts, costs",
            "parameters": {"type": "object", "properties": {}, "required": []},
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_logs",
            "description": "Recent proxym logs",
            "parameters": {
                "type": "object",
                "properties": {
                    "lines": {"type": "integer", "description": "Number of log lines (default 50)"},
                    "level": {
                        "type": "string",
                        "enum": ["all", "error", "warn", "info"],
                        "description": "Log level filter",
                    },
                },
                "required": [],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "list_models",
            "description": "List available AI models with prices",
            "parameters": {"type": "object", "properties": {}, "required": []},
        },
    },
]
