"""
Configuration utilities for the Stiftung application
"""

from django.conf import settings

from stiftung.models import AppConfiguration


def get_config(key, default=None, fallback_to_settings=True):
    """
    Get a configuration value from the database or fall back to Django settings

    Args:
        key: The configuration key
        default: Default value if not found
        fallback_to_settings: If True, try to get from Django settings using the key in uppercase

    Returns:
        The configuration value
    """
    # Try to get from AppConfiguration first
    value = AppConfiguration.get_setting(key, None)

    # Fall back to Django settings if value is None or empty string
    if not value and fallback_to_settings:
        settings_key = key.upper()
        return getattr(settings, settings_key, default)

    return value if value is not None else default


def set_config(key, value, **kwargs):
    """
    Set a configuration value

    Args:
        key: The configuration key
        value: The value to set
        **kwargs: Additional parameters for AppConfiguration.set_setting

    Returns:
        AppConfiguration: The configuration object
    """
    return AppConfiguration.set_setting(key, value, **kwargs)

