"""
Configuration module for AuthManager capability.

Supports loading sensitive values from environment variables.
"""

import os
from dataclasses import dataclass, field
from typing import List, Optional

from ..exceptions.auth_exceptions import ConfigurationError


@dataclass
class AuthConfig:
    """
    Configuration for authentication provider.

    Sensitive values (jwks_url, issuer) can be set via environment variables:
        - NEURONOS_AUTH_JWKS_URL
        - NEURONOS_AUTH_ISSUER
        - NEURONOS_AUTH_PROVIDER

    Attributes:
        provider: Auth provider name (e.g., "clerk")
        jwks_url: URL to the JWKS endpoint for token verification
        issuer: Expected token issuer (optional, for extra validation)
        algorithms: Allowed JWT signing algorithms
        audience: Expected audience claim (optional)
        org_id: Lock to a specific organization ID (optional)
        auto_error: If True, raise HTTPException on auth failure (default True)
    """

    provider: str = ""
    jwks_url: str = ""
    issuer: Optional[str] = None
    algorithms: List[str] = field(default_factory=lambda: ["RS256"])
    audience: Optional[str] = None
    org_id: Optional[str] = None
    auto_error: bool = True

    def __post_init__(self):
        # Resolve from env variables if not provided directly
        self.provider = self.provider or os.getenv("NEURONOS_AUTH_PROVIDER", "clerk")
        self.jwks_url = self.jwks_url or os.getenv("NEURONOS_AUTH_JWKS_URL", "")
        self.issuer = self.issuer or os.getenv("NEURONOS_AUTH_ISSUER") or None

        if not self.jwks_url:
            raise ConfigurationError(
                "jwks_url is required. Set it directly or via NEURONOS_AUTH_JWKS_URL env variable."
            )

        valid_providers = ["clerk"]
        if self.provider.lower() not in valid_providers:
            raise ConfigurationError(
                f"Invalid provider '{self.provider}'. Supported: {', '.join(valid_providers)}"
            )

        self.provider = self.provider.lower()

    def to_dict(self) -> dict:
        return {
            "provider": self.provider,
            "jwks_url": self.jwks_url,
            "issuer": self.issuer,
            "algorithms": self.algorithms,
            "audience": self.audience,
            "org_id": self.org_id,
            "auto_error": self.auto_error,
        }

    @classmethod
    def from_dict(cls, config_dict: dict) -> "AuthConfig":
        return cls(**config_dict)
