"""Azure OpenAI provider settings."""

from pydantic import SecretStr, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


class AzureOpenAISettings(BaseSettings):
    """
    Azure OpenAI service configuration.

    Reads from environment variables with the prefix ``AZURE_OPENAI_``.
    """

    model_config = SettingsConfigDict(env_prefix="AZURE_OPENAI_", extra="ignore")

    endpoint: str
    api_version: str | None = None
    chat_deployment_name: str | None = None
    embedding_deployment_name: str | None = None
    api_key: SecretStr | None = None


class AzureServicePrincipalSettings(BaseSettings):
    """
    Azure AD service principal identity settings for certificate-based auth.

    Reads from environment variables with the prefix ``AZURE_``.
    """

    model_config = SettingsConfigDict(env_prefix="AZURE_", extra="ignore")

    tenant_id: str
    client_id: str
    cognitive_scope: str
    client_certificate_secret: SecretStr
    client_private_key_secret: SecretStr

    @model_validator(mode="after")
    def _normalize_cognitive_scope(self) -> "AzureServicePrincipalSettings":
        """Ensure ``cognitive_scope`` always ends with ``/.default``."""
        if not self.cognitive_scope:
            return self

        scope = self.cognitive_scope.strip()
        if scope.endswith("/.default"):
            self.cognitive_scope = scope
        elif scope.endswith("/"):
            self.cognitive_scope = f"{scope}.default"
        else:
            self.cognitive_scope = f"{scope}/.default"
        return self

    @property
    def certificate_data(self) -> bytes:
        """Combined PEM bytes (certificate + private key)."""
        return (
            self.client_certificate_secret.get_secret_value().encode()
            + b"\n"
            + self.client_private_key_secret.get_secret_value().encode()
        )


__all__ = ["AzureOpenAISettings", "AzureServicePrincipalSettings"]
