"""Authentication module for Azure Discovery API."""

from enum import Enum
from typing import Protocol, Dict, Any, Optional

from .models import UserContext
from .azure_ad import AzureADAuthProvider
from .api_key import APIKeyAuthProvider


class AuthBackend(str, Enum):
    """Supported authentication backends."""
    AZURE_AD = "azure_ad"
    API_KEY = "api_key"
    NONE = "none"  # Development only


class AuthProvider(Protocol):
    """Protocol for authentication providers."""
    
    async def authenticate(self, token: str) -> Dict[str, Any]:
        """Validate token and return user context.
        
        Args:
            token: Authentication token (JWT or API key)
            
        Returns:
            User context dictionary containing identity and permissions
            
        Raises:
            AuthenticationError: If token is invalid or expired
        """
        ...


_auth_provider: Optional[AuthProvider] = None


def initialize_auth(backend: AuthBackend, config: Dict[str, Any]) -> None:
    """Initialize the global authentication provider.
    
    Args:
        backend: Authentication backend to use
        config: Backend-specific configuration
    """
    global _auth_provider
    
    if backend == AuthBackend.AZURE_AD:
        _auth_provider = AzureADAuthProvider(
            tenant_id=config["tenant_id"],
            client_id=config["client_id"],
            audience=config.get("audience", "api://azure-discovery"),
        )
    elif backend == AuthBackend.API_KEY:
        _auth_provider = APIKeyAuthProvider(
            keys=config.get("keys", {}),
        )
    elif backend == AuthBackend.NONE:
        _auth_provider = None
    else:
        raise ValueError(f"Unsupported auth backend: {backend}")


def get_auth_provider() -> Optional[AuthProvider]:
    """Get the current authentication provider.
    
    Returns:
        Current auth provider or None if auth is disabled
    """
    return _auth_provider


__all__ = [
    "AuthBackend",
    "AuthProvider",
    "UserContext",
    "AzureADAuthProvider",
    "APIKeyAuthProvider",
    "initialize_auth",
    "get_auth_provider",
]
