"""
Slack MCP Server — FastMCP instance with all tools registered.

This is the core server module. Tools are organized by domain
in the tools/ subpackage and registered here.
"""

import logging
import sys

from fastmcp import FastMCP

from slack_mcp_server.config import SlackConfig
from slack_mcp_server.tools.messaging import register_messaging_tools
from slack_mcp_server.tools.channels import register_channel_tools
from slack_mcp_server.tools.search import register_search_tools
from slack_mcp_server.tools.reactions import register_reaction_tools
from slack_mcp_server.tools.users import register_user_tools
from slack_mcp_server.tools.files import register_file_tools

# Ensure logging goes to stderr (required for stdio MCP transport)
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
    stream=sys.stderr,
)

logger = logging.getLogger("slack_mcp_server")


def create_server() -> FastMCP:
    """Create and configure the Slack MCP server.

    Validates environment configuration on startup and registers
    all Slack tools with the FastMCP instance.
    """
    # Validate config on startup
    config = SlackConfig()
    config.validate_or_exit()

    app = FastMCP(
        name="slack-mcp-server",
        instructions=(
            "MCP server for Slack workspace operations. "
            "Send messages, manage channels, search conversations, "
            "react to messages, manage files, and look up user profiles."
        ),
        version="1.0.2",
    )

    # Register all tool groups
    register_messaging_tools(app, config)
    register_channel_tools(app, config)
    register_search_tools(app, config)
    register_reaction_tools(app, config)
    register_user_tools(app, config)
    register_file_tools(app, config)

    logger.info("Slack MCP server configured with all tool groups")
    return app
