"""
Main DRFMCP Server Class

High-level API for setting up and running an MCP server for Django REST Framework.
"""

import logging
from typing import Optional, Type

from fastmcp import FastMCP as BaseFastMCP

from drf_mcp.provider import DRFProvider

logger = logging.getLogger(__name__)


class DRFMCP:
    """
    High-level Django REST Framework MCP Server.
    
    Simplifies integration of DRF views with Model Context Protocol.
    
    Usage:
        mcp = DRFMCP("MyAPI")
        mcp.register_viewset(CustomerViewSet, namespace="crm")
        mcp.run()
    """

    def __init__(
        self,
        name: str,
        version: str = "0.1.0",
        description: Optional[str] = None,
    ):
        """
        Initialize DRFMCP server.
        
        Args:
            name: Name of the MCP server
            version: Server version
            description: Server description
        """
        self.name = name
        self.version = version
        self.description = description or f"Django REST Framework MCP Server: {name}"
        
        # Initialize FastMCP
        self._fastmcp = BaseFastMCP(
            name=name,
            version=version,
        )
        
        # Initialize DRFProvider
        self.provider = DRFProvider(namespace="drf")
        
        logger.info(f"Initialized DRFMCP server: {name} v{version}")

    def register_viewset(
        self,
        viewset_class: Type,
        namespace: Optional[str] = None,
    ) -> None:
        """
        Register a DRF ViewSet to be exposed as MCP tools.
        
        Args:
            viewset_class: ViewSet class to register
            namespace: Optional namespace prefix for tools
        """
        self.provider.register_viewset(viewset_class, namespace=namespace)
        logger.info(f"Registered ViewSet: {viewset_class.__name__}")

    def register_apiview(
        self,
        view_class: Type,
        namespace: Optional[str] = None,
    ) -> None:
        """
        Register a DRF APIView to be exposed as MCP tools.
        
        Args:
            view_class: APIView class to register
            namespace: Optional namespace prefix for tools
        """
        self.provider.register_apiview(view_class, namespace=namespace)
        logger.info(f"Registered APIView: {view_class.__name__}")

    def autodiscover(self, namespace: Optional[str] = None) -> int:
        """
        Automatically discover all DRF views in URLconf and expose as tools.
        
        Args:
            namespace: Optional namespace prefix for tools
            
        Returns:
            Number of tools registered
        """
        count = self.provider.autodiscover(namespace=namespace)
        logger.info(f"Autodiscovered {count} MCP tools from DRF views")
        return count

    def run(self, **kwargs) -> None:
        """
        Run the MCP server.
        
        Supports stdio, HTTP, and SSE transport via FastMCP.
        
        Args:
            **kwargs: Additional arguments passed to FastMCP.run()
        """
        logger.info(f"Starting DRFMCP server: {self.name}")
        self._fastmcp.run(**kwargs)

    def get_server(self) -> BaseFastMCP:
        """
        Get the underlying FastMCP server instance for advanced customization.
        
        Returns:
            FastMCP server instance
        """
        return self._fastmcp
