import os
from typing import Callable, Optional

from risc_lasagna.helper import normalize_variable_prefix
from risc_lasagna.layer.dict_layer import DictLayer


class _EnvironmentLayer(DictLayer):
    pass


def EnvironmentLayer(
    variable_prefix: Optional[str] = None,
    capitalize_keys: bool = True,
    normalize_prefix: Callable[[str], str] = normalize_variable_prefix,
):
    """
    Provides access to os.environ keys. Filters the environment by a given variable_prefix if given.
    """
    """
    Creates an environment layer which can be scorped by a variable prefix.
    :param variable_prefix: The variable prefix which is added to every key
    :param capitalize_keys: If keys should be capitalized for access
    """
    # filter for the prefix (avoids importing whole environment)
    if variable_prefix is not None:
        map_ = {
            key: os.environ[key]
            for key in os.environ.keys()
            if key.startswith(variable_prefix)
        }
    else:
        map_ = dict(os.environ)

    if capitalize_keys:
        map_ = {key.upper(): value for key, value in map_.items()}

    return _EnvironmentLayer(
        map_,
        variable_prefix=variable_prefix,
        capitalize_keys=capitalize_keys,
        normalize_prefix=normalize_prefix,
    )
