"""
Authentication utility functions for creating token providers.

Supports DefaultAzureCredential, certificate-based, and pre-fetched token auth.
"""

from typing import Callable


def get_default_token_provider() -> Callable[[], str]:
    """Create a token provider using DefaultAzureCredential."""
    try:
        from azure.identity import DefaultAzureCredential, get_bearer_token_provider
    except ImportError:
        raise ImportError(
            "azure-identity is required for DefaultAzureCredential. "
            "Install with: pip install azure-identity"
        )

    credentials = DefaultAzureCredential()
    token_provider = get_bearer_token_provider(
        credentials, "https://cognitiveservices.azure.com/.default"
    )
    return token_provider


def get_certificate_token_provider(
    tenant_id: str,
    client_id: str,
    certificate_data: bytes,
    scope: str = "https://cognitiveservices.azure.com/.default",
) -> Callable[[], str]:
    """Create a token provider using X.509 certificate authentication."""
    try:
        from azure.identity import CertificateCredential
    except ImportError:
        raise ImportError(
            "azure-identity is required for CertificateCredential. "
            "Install with: pip install azure-identity"
        )

    credential = CertificateCredential(
        tenant_id=tenant_id,
        client_id=client_id,
        certificate_data=certificate_data,
    )

    def token_provider() -> str:
        token = credential.get_token(scope)
        return token.token

    return token_provider


def create_token_provider_from_string(token: str) -> Callable[[], str]:
    """Create a simple token provider from a pre-authenticated token."""

    def token_provider() -> str:
        return token

    return token_provider


__all__ = [
    "get_default_token_provider",
    "get_certificate_token_provider",
    "create_token_provider_from_string",
]
