"""MCP server for Camoufox browser automation."""

import asyncio
import signal
import sys

from mcp.server.fastmcp import FastMCP

from .browser import browser_manager
from .tools import forms, interaction, navigation, page, session

# Create the MCP server
mcp = FastMCP(
    "camoufox-mcp",
    instructions="Browser automation with Camoufox anti-detection capabilities",
)

# Register all tools
navigation.register(mcp)
interaction.register(mcp)
page.register(mcp)
forms.register(mcp)
session.register(mcp)


async def cleanup() -> None:
    """Clean up browser resources on shutdown."""
    await browser_manager.close()


def handle_shutdown(sig: signal.Signals, frame: object) -> None:
    """Handle shutdown signals."""
    asyncio.create_task(cleanup())
    sys.exit(0)


def main() -> None:
    """Run the MCP server."""
    # Register signal handlers for graceful shutdown
    signal.signal(signal.SIGINT, handle_shutdown)
    signal.signal(signal.SIGTERM, handle_shutdown)

    try:
        mcp.run()
    finally:
        # Ensure cleanup on normal exit
        asyncio.run(cleanup())


if __name__ == "__main__":
    main()
