"""MCP tools — Account management."""
from __future__ import annotations

from typing import Any

from fastapi import APIRouter
from pydantic import BaseModel, Field

from proxym.mcp._helpers import _get_dashboard

router = APIRouter()


# ── Request models ────────────────────────────────────────

class AccountAddRequest(BaseModel):
    provider: str = Field(..., description="Provider: anthropic | openrouter | openai | google | deepseek")
    api_key: str = Field(..., description="API key")
    label: str = Field("", description="Human-readable label")
    budget_usd: float = Field(5.0, description="Daily budget in USD")


# ── Endpoints ─────────────────────────────────────────────

@router.post("/tools/account_list")
async def tool_account_list() -> dict[str, Any]:
    """List all accounts with costs."""
    try:
        _, _accounts = _get_dashboard()
        accts = _accounts().list_accounts()
        return {"accounts": accts}
    except Exception as exc:
        return {"accounts": [], "error": str(exc)}


@router.post("/tools/account_costs")
async def tool_account_costs() -> dict[str, Any]:
    """Cost summary per account and model."""
    try:
        _, _accounts = _get_dashboard()
        return _accounts().get_cost_summary()
    except Exception as exc:
        return {"error": str(exc)}


@router.post("/tools/account_add")
async def tool_account_add(req: AccountAddRequest) -> dict[str, Any]:
    """Add a new API account."""
    try:
        _, _accounts = _get_dashboard()
        result = _accounts().add_account(
            provider=req.provider, api_key=req.api_key,
            label=req.label, budget_usd=req.budget_usd,
        )
        return {"status": "added", "account": result}
    except Exception as exc:
        return {"status": "error", "error": str(exc)}


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

TOOL_SCHEMA_ACCOUNTS: list[dict[str, Any]] = [
    {
        "type": "function",
        "function": {
            "name": "get_costs",
            "description": "Cost summary: daily, monthly, per account, per model",
            "parameters": {"type": "object", "properties": {}, "required": []},
        },
    },
]
