"""
Utility for retrieving configuration values from multiple sources.

See Also:
    docs/reference/what-is-the-modules-folder.md
    docs/howtos/how-to-write-a-fetch-function.md
"""

import os
from dotenv import load_dotenv

load_dotenv()


def params_or_env(connection, source, key, default=None):
    """
    Get a configuration value from environment, connection params, or source params.

    Lookup order (first match wins):
        1. Environment variable
        2. connection.params[key]
        3. source.params[key]
        4. default value

    Args:
        connection: Connection config object (may have .params dict)
        source: Source config object (may have .params dict)
        key: The key to look up
        default: Value to return if key not found (default: None)

    Returns:
        The value if found, otherwise the default value

    Example:
        # Get API key with fallback
        api_key = params_or_env(connection, source, 'API_KEY', default='default-key')

        # Get required value (will raise KeyError if not found)
        token = params_or_env(connection, source, 'TOKEN') or error()
    """
    # 1. Check environment first (highest priority)
    if key in os.environ:
        return os.environ[key]

    # 2. Check connection params
    if connection and connection.params and key in connection.params:
        return connection.params[key]

    # 3. Check source params
    if source and source.params and key in source.params:
        return source.params[key]

    # 4. Return default if not found anywhere
    return default
