"""Shared global state and lazy initializers for API endpoints."""

from __future__ import annotations

from proxym.cache import DeltaBuffer
from proxym.config import get_settings
from proxym.context import SessionStore
from proxym.mcp import MCPRegistry, MCPRouter
from proxym.router.strategy import CostLedger, Router
from proxym.utils.get_settings import get_singleton

_router: Router | None = None
_delta_buffer: DeltaBuffer | None = None
_context_payload: str = ""
_mcp_registry: MCPRegistry | None = None
_mcp_router: MCPRouter | None = None
_session_store: SessionStore | None = None


def get_router() -> Router:
    global _router
    if _router is None:
        settings = get_settings()
        providers = set(settings.available_providers().keys())
        ledger = CostLedger(
            daily_limit=settings.daily_budget_usd,
            monthly_limit=settings.monthly_budget_usd,
            redis_url=settings.redis_url,
        )
        _router = Router(
            available_providers=providers,
            ledger=ledger,
            max_request_cost=settings.max_request_cost_usd,
        )
    return _router


def get_delta_buffer() -> DeltaBuffer:
    global _delta_buffer
    if _delta_buffer is None:
        settings = get_settings()
        _delta_buffer = DeltaBuffer(
            watch_dir=settings.watch_dir,
            max_context_tokens=settings.max_context_tokens,
            delta_threshold=settings.delta_threshold,
        )
    return _delta_buffer


def get_mcp_router() -> MCPRouter:
    global _mcp_registry, _mcp_router
    if _mcp_router is None:
        _mcp_registry = MCPRegistry()
        # Register builtin proxym-self MCP server
        from proxym.mcp.registry import MCPServerSpec, MCPTransport
        settings = get_settings()
        _mcp_registry.register(MCPServerSpec(
            name="proxym-self",
            url=f"http://localhost:{settings.port}/mcp/self",
            transport=MCPTransport.HTTP,
            description="Proxym self-management: VMs, accounts, costs, logs",
            tools=[
                "vm_list", "vm_create", "vm_start", "vm_stop", "vm_snapshot",
                "vm_switch_project", "account_list", "account_costs",
                "account_add", "status", "logs", "models",
            ],
            priority=1,
        ))
        _mcp_router = MCPRouter(_mcp_registry)
    return _mcp_router


def get_session_store() -> SessionStore:
    global _session_store
    _session_store = get_singleton(_session_store, SessionStore)
    return _session_store


def get_context_payload() -> str:
    return _context_payload


def set_context_payload(payload: str) -> None:
    global _context_payload
    _context_payload = payload
