"""FastMCP server for the Cloudflare MCP Gateway."""

import logging

from fastmcp import Client, FastMCP
from fastmcp.client.transports import StreamableHttpTransport

from .config import GatewaySettings
from .registry import ServiceRegistry

logger = logging.getLogger(__name__)

# Global state for the gateway
_settings: GatewaySettings | None = None
_registry: ServiceRegistry | None = None
_clients: dict[str, Client] = {}

# Create the FastMCP server instance
mcp = FastMCP(
    "Cloudflare MCP Gateway",
    instructions="A unified gateway for accessing multiple Cloudflare services. "
    "Tools are prefixed with the service name (e.g., docs_, kv_, r2_).",
)


async def initialize_gateway(settings: GatewaySettings) -> None:
    """Initialize the gateway with settings.

    Args:
        settings: Gateway configuration settings.
    """
    global _settings, _registry

    _settings = settings
    _registry = ServiceRegistry(settings)

    logger.info(
        f"Initialized registry with {len(_registry)} services: "
        f"{', '.join(s.id for s in _registry)}"
    )


async def connect_and_mount_services() -> None:
    """Connect to all enabled upstream services and mount them."""
    global _clients

    if not _registry or not _settings:
        raise RuntimeError("Gateway not initialized. Call initialize_gateway() first.")

    auth_headers = {
        "Authorization": f"Bearer {_settings.cloudflare_api_token}",
        "CF-Account-ID": _settings.cloudflare_account_id,
    }

    for service in _registry.get_enabled_services():
        try:
            logger.info(f"Connecting to {service.id} at {service.endpoint}")

            # Create transport with authentication headers
            transport = StreamableHttpTransport(url=service.endpoint, headers=auth_headers)

            # Create a Client for the upstream MCP server
            client = Client(transport)

            # Create a proxy server from this client and mount it with prefix
            proxy = FastMCP.as_proxy(client, name=f"{service.id}_proxy")

            # Mount the proxy with the service ID as prefix
            mcp.mount(proxy, prefix=service.id)

            _clients[service.id] = client
            logger.info(f"Successfully mounted {service.id} with prefix '{service.id}_'")

        except Exception as e:
            logger.warning(f"Failed to connect to {service.id}, will skip: {e}")


async def shutdown_gateway() -> None:
    """Perform graceful shutdown of the gateway."""
    global _clients

    logger.info("Shutting down gateway...")
    _clients = {}
    logger.info("Gateway shutdown complete")
