#!/usr/bin/env python3
"""
Main entry point for Microsoft Sentinel MCP Server.
This module serves as the primary entry point for the MCP server.
"""

import sys
import signal
import asyncio
from pathlib import Path

# Add the current directory to the path
current_dir = Path(__file__).parent.absolute()
sys.path.insert(0, str(current_dir))

# Import the server module
from server import mcp, logger


def main(port: int = 8000, transport: str = None):
    """Main entry point for the MCP server."""

    # Set up signal handlers for graceful shutdown
    def signal_handler(_sig, _frame):
        logger.info("Shutdown signal received, exiting gracefully...")

    # Register the signal handler for SIGINT (CTRL+C)
    signal.signal(signal.SIGINT, signal_handler)

    try:
        # Let MCP CLI handle the transport configuration
        logger.info("Running server... transport=%s, port=%s", transport, port)
        mcp.run()
    except KeyboardInterrupt:
        logger.info("Keyboard interrupt received, shutting down...")
        sys.exit(0)
    except asyncio.CancelledError:
        logger.info(
            "Asyncio CancelledError received during shutdown, exiting cleanly..."
        )
        sys.exit(0)
    except Exception as e:
        logger.error("Error starting server: %s", e, exc_info=True)
        sys.exit(1)


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="Microsoft Sentinel MCP Server")
    parser.add_argument(
        "--sse",
        action="store_true",
        help="Run server in SSE (HTTP) mode instead of STDIO",
    )
    parser.add_argument(
        "--port",
        "-p",
        type=int,
        default=8000,
        help="Port for SSE server (default: 8000)",
    )
    args = parser.parse_args()
    main(port=args.port, transport="sse" if args.sse else None)