"""FastMCP server definition for Komodo Health Assistant.

This server provides tools for working with the Komodo Health platform,
including Snowflake data exploration.
"""

import logging
import os
import sys

from fastmcp import FastMCP

from .prompts import LIST_SNOWFLAKE_DESCRIPTION, SERVER_INSTRUCTIONS

# =============================================================================
# Logging Configuration
# =============================================================================


def _configure_logging() -> None:
    """Configure logging for the MCP server.

    Logs are written to stderr so they're visible in MCP logs.
    Set KOM_MCP_LOG_LEVEL environment variable to control verbosity:
    - DEBUG: All debug information (default when KOM_MCP_DEBUG=1)
    - INFO: Normal operation logs (default)
    - WARNING: Only warnings and errors
    - ERROR: Only errors
    """
    log_level_name = os.getenv("KOM_MCP_LOG_LEVEL", "INFO").upper()

    # Allow KOM_MCP_DEBUG=1 to enable debug logging
    if os.getenv("KOM_MCP_DEBUG", "0") == "1":
        log_level_name = "DEBUG"

    log_level = getattr(logging, log_level_name, logging.INFO)

    # Configure the kom_mcp logger namespace
    kom_logger = logging.getLogger("kom_mcp")
    kom_logger.setLevel(log_level)

    # Remove any existing handlers to avoid duplicates
    for handler in kom_logger.handlers[:]:
        kom_logger.removeHandler(handler)

    # Create stderr handler
    handler = logging.StreamHandler(sys.stderr)
    handler.setLevel(log_level)

    # Use a clear format with timestamps
    formatter = logging.Formatter("[%(asctime)s] %(levelname)-8s [%(name)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
    handler.setFormatter(formatter)
    kom_logger.addHandler(handler)

    # Don't propagate to root logger
    kom_logger.propagate = False

    kom_logger.info(f"Logging configured at level: {log_level_name}")


# Configure logging immediately when module loads
_configure_logging()

logger = logging.getLogger("kom_mcp.server")


# Create the FastMCP server instance
mcp = FastMCP(
    name="Komodo Health Assistant",
    instructions=SERVER_INSTRUCTIONS,
)


def run_server() -> None:
    """Run the MCP server with STDIO transport."""
    from importlib.metadata import entry_points

    logger.info("=" * 60)
    logger.info("Starting Komodo Health Assistant MCP Server")
    logger.info("=" * 60)

    logger.debug("Loading tools modules...")
    from .snowflake_tools import list_snowflake

    mcp.tool(description=LIST_SNOWFLAKE_DESCRIPTION)(list_snowflake)

    logger.info("Core tools loaded successfully")

    for ep in entry_points(group="komodo.mcp_plugins"):
        try:
            register_fn = ep.load()
            register_fn(mcp)
            logger.info(f"Loaded MCP plugin: {ep.name}")
        except Exception as e:
            logger.debug(f"Failed to load MCP plugin '{ep.name}': {e}")

    logger.info("Starting server with STDIO transport...")
    mcp.run()


if __name__ == "__main__":
    run_server()
