"""
Environment configuration loader for Aniworld application.

This module provides unified configuration loading based on the environment
(development, production, or testing). It automatically selects the appropriate
settings configuration based on the ENVIRONMENT variable.
"""

import os
from typing import Union

from .development import DevelopmentSettings, get_development_settings
from .production import ProductionSettings, get_production_settings

# Environment options
ENVIRONMENT = os.getenv("ENVIRONMENT", "development").lower()

# Valid environment values
VALID_ENVIRONMENTS = {"development", "production", "testing"}

if ENVIRONMENT not in VALID_ENVIRONMENTS:
    raise ValueError(
        f"Invalid ENVIRONMENT '{ENVIRONMENT}'. "
        f"Must be one of: {VALID_ENVIRONMENTS}"
    )


def get_settings() -> Union[DevelopmentSettings, ProductionSettings]:
    """
    Get environment-specific settings.

    Returns:
        DevelopmentSettings: If ENVIRONMENT is 'development' or 'testing'
        ProductionSettings: If ENVIRONMENT is 'production'

    Raises:
        ValueError: If ENVIRONMENT is not valid

    Example:
        >>> settings = get_settings()
        >>> print(settings.log_level)
        INFO
    """
    if ENVIRONMENT in {"development", "testing"}:
        return get_development_settings()
    return get_production_settings()


# Singleton instance - loaded on first call
_settings_instance = None


def _get_settings_cached() -> Union[DevelopmentSettings, ProductionSettings]:
    """Get cached settings instance."""
    global _settings_instance
    if _settings_instance is None:
        _settings_instance = get_settings()
    return _settings_instance


# Re-export for convenience
__all__ = [
    "get_settings",
    "ENVIRONMENT",
    "DevelopmentSettings",
    "ProductionSettings",
    "get_development_settings",
    "get_production_settings",
]
