#!/usr/bin/env python3
"""
Main entry point for the BuboBot MCP Server

This script initializes and runs the Model Context Protocol (MCP) server
that provides tools for AI model integration.
"""

import asyncio
import logging
import argparse
import sys
import os

from bubobot_mcp.src.mcp_server.server import MCPServer
from bubobot_mcp.src.config.config import Config
from bubobot_mcp.src.utils.setup_logging import setup_logging
from bubobot_mcp.src.utils.custom_error import CustomError
from bubobot_mcp.src.constants.error_codes import ErrorCodeValidator


async def main() -> None:
    """
    Main entry point for the MCP server application.
    
    Initializes configuration, logging, and starts the MCP server.
    """
    logger = logging.getLogger(__name__)

    try:
        # Get directory containing this file
        current_dir = os.path.dirname(os.path.abspath(__file__))
        
        # Initialize configuration with absolute paths
        config = Config(
            base_config_path=os.path.join(current_dir, "src", "config", "base_config.yml"),
            env_file_path=os.path.join(current_dir, ".env")
        )

        # Setup logging
        setup_logging(config=config)

        logger.info("Starting BuboBot MCP Server...")
        logger.info(f"MCP Server Name: {config.mcp_server_name}")
        logger.info(f"MCP Server Version: {config.mcp_server_version}")
        
        # Create MCP server
        server = MCPServer(config=config)
        
        # Parse command line arguments
        parser = argparse.ArgumentParser(description='BuboBot MCP Server')
        parser.add_argument('--transport', type=str, default='stdio',
                          choices=['stdio', 'http'],
                          help='Transport mode: stdio, http (default: stdio)')
        args = parser.parse_args()
        transport_mode = args.transport.lower()
        
        if transport_mode == "http":
            # HTTP transport for multiple concurrent clients
            logger.info(f"Using HTTP transport on {server.config.http_host}:{server.config.http_port}")
            await server.run_http()  # Async call
        else:
            # Default stdio transport for single client (backward compatibility)
            logger.info("Using stdio transport")
            await server.run_stdio()

    except KeyboardInterrupt:
        logger.info("Server shutdown requested by user")
        sys.exit(0)

    except CustomError as ce:
        if ErrorCodeValidator.is_server_error(ce.code):
            logger.error(f"Server error: {ce.message}")
            sys.exit(ce.code)

    except Exception as e:
        logger.error(f"Session error: {e}")
        logger.info("Restarting server for next connection...")
        
        await asyncio.sleep(1)


if __name__ == "__main__":
    asyncio.run(main())
