"""
OAuth2/OIDC Authentication Integration Example

Demonstrates secure MCP server setup with OAuth2 and OIDC authentication,
following security best practices for production deployments.
"""

from drf_spectacular.openapi import AutoSchema
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, permission_classes
from drf_mcp.auth import OAuthValidator, OIDCValidator
from drf_mcp.provider import MCPProvider


# OAuth2 Configuration
oauth_config = {
    'client_id': 'your-client-id',
    'client_secret': 'your-client-secret',
    'token_url': 'https://auth-provider.com/token',
    'authorize_url': 'https://auth-provider.com/authorize',
    'scopes': ['read', 'write']
}

# OIDC Configuration
oidc_config = {
    'provider': 'https://accounts.google.com',
    'client_id': 'your-client-id',
    'client_secret': 'your-client-secret',
    'scopes': ['openid', 'email', 'profile']
}


# Initialize validators
oauth_validator = OAuthValidator(oauth_config)
oidc_validator = OIDCValidator(oidc_config)


# Protected endpoint requiring OAuth2 token
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def protected_resource(request):
    """
    This endpoint requires a valid OAuth2 token.
    
    The token should be passed in the Authorization header:
    Authorization: Bearer {access_token}
    """
    # Token is automatically validated by Django REST Framework
    # and request.user is populated with the authenticated user
    
    return {
        'message': f'Hello, {request.user.username}!',
        'authenticated': True,
        'scopes': request.auth.scope if hasattr(request, 'auth') else []
    }


# Initialize MCP Provider with authentication
provider = MCPProvider()

# Configure authentication for MCP tools
provider.set_auth_validator(oauth_validator)
# or for OIDC:
# provider.set_auth_validator(oidc_validator)


# Example: Conditional tool exposure based on scopes
def get_admin_tools(request):
    """
    Return admin tools only for users with 'admin' scope.
    """
    tools = {}
    
    if hasattr(request, 'auth') and 'admin' in request.auth.scope:
        tools['delete_user'] = provider.get_tool('delete_user')
        tools['modify_permissions'] = provider.get_tool('modify_permissions')
    
    return tools


# Usage in MCP Server
if __name__ == "__main__":
    from fastmcp import Server
    
    mcp_server = Server("django-mcp-secure")
    
    # Tools will only be accessible with valid OAuth2/OIDC tokens
    for tool_name, tool_handler in provider.get_tools().items():
        mcp_server.tool(tool_handler)
    
    print("Secure MCP Server initialized with authentication")
