#!/usr/bin/env python3
"""
CAST.AI External MCP Server

Provides Model Context Protocol tools for interacting with the CAST.AI API.
This is a simplified, customer-facing version that uses API key authentication
and provides cluster management tools.
"""

import logging
import sys

from fastmcp import FastMCP

from .config import API_KEY
from .logger import logger
from .tools.clusters import register_cluster_tools
from .tools.cost import register_cost_tools
from .tools.policies import register_policy_tools
from .tools.woop import register_workload_tools


# Configure unified logfmt logging for all Python loggers
class LogfmtHandler(logging.Handler):
    """
    Custom logging handler that converts standard Python logging to logfmt format.

    This captures logs from FastMCP, httpx, and other libraries that use
    Python's standard logging module, and formats them consistently with
    our application logs.
    """

    def emit(self, record):
        """Emit a log record in logfmt format."""
        try:
            # Use the StructuredLogger to output in logfmt
            logger_name = record.name if record.name != 'root' else 'python'
            log_entry = {
                'logger': logger_name,
            }

            # Map Python log levels to our logger methods
            if record.levelno >= logging.ERROR:
                logger.error(record.getMessage(), **log_entry)
            elif record.levelno >= logging.WARNING:
                logger.warning(record.getMessage(), **log_entry)
            elif record.levelno >= logging.INFO:
                logger.info(record.getMessage(), **log_entry)
            else:
                logger.debug(record.getMessage(), **log_entry)
        except Exception:
            # Fallback to standard error handling
            self.handleError(record)


# Configure root logger to use logfmt format
# This must be done early, before any libraries initialize their loggers
logging.root.handlers = []
logging.root.addHandler(LogfmtHandler())
logging.root.setLevel(logging.INFO)

# Reduce verbosity of MCP internal logging
logging.getLogger("mcp.server.lowlevel.server").setLevel(logging.WARNING)

# Initialize FastMCP server
mcp = FastMCP("CAST.AI")

# Register all tools
logger.info("Registering MCP tools")
register_cluster_tools(mcp)
register_cost_tools(mcp)
register_policy_tools(mcp)
register_workload_tools(mcp)
logger.info("All MCP tools registered")


def run_server():
    """Entry point for console script."""
    # Validate required configuration
    if not API_KEY:
        logger.error(
            "CASTAI_API_KEY environment variable is required. "
            "Get an API key from https://console.cast.ai > Settings > API Keys"
        )
        sys.exit(1)

    # Run the MCP server with stdio transport (local/Claude Desktop only)
    logger.info("Starting CAST.AI External MCP server", transport="stdio", api_key_configured=bool(API_KEY))
    mcp.run()


if __name__ == "__main__":
    run_server()
