"""
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 get_paperless_config():
    """
    Get all Paperless-related configuration values
    
    Returns:
        dict: Dictionary containing all Paperless configuration
    """
    return {
        'api_url': get_config('paperless_api_url', 'http://192.168.178.167:30070'),
        'api_token': get_config('paperless_api_token', ''),
        'destinataere_tag': get_config('paperless_destinataere_tag', 'Stiftung_Destinatäre'),
        'destinataere_tag_id': get_config('paperless_destinataere_tag_id', '210'),
        'land_tag': get_config('paperless_land_tag', 'Stiftung_Land_und_Pächter'),
        'land_tag_id': get_config('paperless_land_tag_id', '204'),
        'admin_tag': get_config('paperless_admin_tag', 'Stiftung_Administration'),
        'admin_tag_id': get_config('paperless_admin_tag_id', '216'),
    }


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)


def is_paperless_configured():
    """
    Check if Paperless is properly configured
    
    Returns:
        bool: True if API URL and token are configured
    """
    config = get_paperless_config()
    return bool(config['api_url'] and config['api_token'])
