"""Configuration for remem-auth via environment variables."""

import json

from pydantic import ValidationError
from pydantic_settings import BaseSettings

from ._models import IdpConfig


class AuthConfig(BaseSettings):
    """Auth configuration loaded from environment variables.

    All env vars are prefixed with ``REMEM_AUTH_``.
    """

    model_config = {"env_prefix": "REMEM_AUTH_"}

    # Azure Entra ID convenience fields
    azure_tenant_id: str = ""
    azure_client_id: str = ""

    # Google convenience field
    google_client_id: str = ""

    # Advanced: full JSON array of IdpConfig dicts
    idps_json: str = ""

    # Comma-separated static bearer tokens
    static_tokens: str = ""

    # Verification flags
    verify_exp: bool = True
    verify_aud: bool = True

    def get_idp_configs(self) -> list[IdpConfig]:
        """Build the list of IdP configurations from settings."""
        if self.idps_json:
            try:
                raw = json.loads(self.idps_json)
                return [IdpConfig(**entry) for entry in raw]
            except (json.JSONDecodeError, TypeError, ValidationError) as exc:
                raise ValueError(f"Invalid REMEM_AUTH_IDPS_JSON: {exc}") from exc

        configs: list[IdpConfig] = []

        if self.azure_tenant_id and self.azure_client_id:
            configs.append(
                IdpConfig(
                    name="azure",
                    issuer=f"https://login.microsoftonline.com/{self.azure_tenant_id}/v2.0",
                    jwks_uri=(
                        f"https://login.microsoftonline.com/{self.azure_tenant_id}"
                        "/discovery/v2.0/keys"
                    ),
                    audience=self.azure_client_id,
                )
            )

        if self.google_client_id:
            configs.append(
                IdpConfig(
                    name="google",
                    issuer="https://accounts.google.com",
                    jwks_uri="https://www.googleapis.com/oauth2/v3/certs",
                    audience=self.google_client_id,
                )
            )

        return configs

    def get_static_token_set(self) -> set[str]:
        """Parse comma-separated static tokens into a set."""
        if not self.static_tokens:
            return set()
        return {t.strip() for t in self.static_tokens.split(",") if t.strip()}

    @property
    def auth_enabled(self) -> bool:
        """True if any IdP or static token is configured."""
        return bool(self.get_idp_configs() or self.get_static_token_set())


def create_auth_config_from_env() -> AuthConfig:
    """Factory that instantiates AuthConfig from environment variables."""
    return AuthConfig()
