"""Azure integration hooks -- optional, requires the `azure` extra
(`pip install a2a-passport[azure]`).

Two things an agent running on (or talking to) Azure needs:

1. Verifying tokens issued by Microsoft Entra ID (formerly Azure AD) --
   entra_id_verifier() derives the JWKS URI and issuer from your tenant ID.
2. Pulling a client secret out of Azure Key Vault at startup instead of
   hardcoding it -- secret_from_key_vault() uses azure-identity's
   DefaultAzureCredential, which picks up a managed identity, environment
   variables, or `az login` automatically, in that order.
"""
from __future__ import annotations

from a2a_passport.auth.verifiers import JWKSVerifier


def entra_id_verifier(*, tenant_id: str) -> JWKSVerifier:
    """JWKSVerifier pre-configured for a Microsoft Entra ID (Azure AD) tenant.

    Pair this with a caller that presents an Entra ID-issued token -- e.g.
    an Azure-hosted agent calling into a GCP- or AWS-hosted one.
    """
    issuer = f"https://login.microsoftonline.com/{tenant_id}/v2.0"
    jwks_uri = f"https://login.microsoftonline.com/{tenant_id}/discovery/v2.0/keys"
    return JWKSVerifier(jwks_uri=jwks_uri, issuer=issuer)


def secret_from_key_vault(vault_url: str, secret_name: str) -> str:
    """Fetch a secret value from Azure Key Vault.

    Uses DefaultAzureCredential -- picks up a managed identity when running
    on Azure, or environment variables / `az login` locally. No credentials
    need to be passed here explicitly in the common case.
    """
    from azure.identity import DefaultAzureCredential
    from azure.keyvault.secrets import SecretClient

    client = SecretClient(vault_url=vault_url, credential=DefaultAzureCredential())
    value = client.get_secret(secret_name).value
    if value is None:
        raise RuntimeError(f"secret {secret_name!r} in {vault_url} has no value")
    return value
