"""
Edupaid client configuration.

Loads and validates configuration from environment variables or constructor arguments.

Required environment variables:
    - EDUPAID_API_KEY: API key for authenticating with the Edupaid API (x-api-key header)
    - EDUPAID_PROVIDER_ID: Provider identifier used in API requests
    - EDUPAID_JWT_SECRET: Secret for JWT operations (webhook signature verification)

Optional environment variables:
    - EDUPAID_ENVIRONMENT: 'production' (default) or 'staging'

Used by: edupaid/client.py to initialize the Edupaid client.
"""

import os
from typing import Literal, Optional

from edupaid.errors import ConfigurationError


# Type alias for allowed environment values
AllowedEnvironment = Literal["production", "staging"]


class Settings:
    """
    Validated client configuration loaded from environment variables.

    Attributes:
        api_key: API key for x-api-key header authentication.
        provider_id: Provider identifier for API requests.
        jwt_secret: Secret for JWT/webhook signature verification.
        environment: Target environment ('production' or 'staging').
        api_base_url: Base URL for the Edupaid API (derived from environment).

    Used by: edupaid/client.py::Edupaid.__init__
    """

    def __init__(
        self,
        api_key: Optional[str] = None,
        provider_id: Optional[str] = None,
        jwt_secret: Optional[str] = None,
        environment: Optional[str] = None,
    ):
        """
        Initialize settings from arguments or environment variables.

        Args:
            api_key: API key (falls back to EDUPAID_API_KEY env var).
            provider_id: Provider ID (falls back to EDUPAID_PROVIDER_ID env var).
            jwt_secret: JWT secret (falls back to EDUPAID_JWT_SECRET env var).
            environment: Environment name (falls back to EDUPAID_ENVIRONMENT, default 'production').

        Raises:
            ConfigurationError: If required variables are missing or environment is invalid.
        """
        # Load from args or environment variables
        self.api_key = api_key or os.getenv("EDUPAID_API_KEY")
        self.provider_id = provider_id or os.getenv("EDUPAID_PROVIDER_ID")
        self.jwt_secret = jwt_secret or os.getenv("EDUPAID_JWT_SECRET")
        self.environment = environment or os.getenv("EDUPAID_ENVIRONMENT", "production")

        # Validate required variables
        missing = []
        if not self.api_key:
            missing.append("EDUPAID_API_KEY")
        if not self.provider_id:
            missing.append("EDUPAID_PROVIDER_ID")
        if not self.jwt_secret:
            missing.append("EDUPAID_JWT_SECRET")

        if missing:
            raise ConfigurationError(
                "Missing required environment variables: " + ", ".join(missing)
            )

        # Validate environment value
        allowed: tuple[str, ...] = ("production", "staging")
        if self.environment not in allowed:
            raise ConfigurationError(
                f"Invalid EDUPAID_ENVIRONMENT='{self.environment}'. Allowed values: {allowed}"
            )

        # Map environment to API base URL
        if self.environment == "production":
            self.api_base_url = "https://api.edupaid.2hourlearning.com/functions/v1"
        elif self.environment == "staging":
            # Placeholder for staging environment
            self.api_base_url = "https://api.staging.edupaid.2hourlearning.com/functions/v1"

        # Normalize: ensure no trailing slash for consistent path joining
        self.api_base_url = self.api_base_url.rstrip("/")
