import os
from intranet.search.settings import entities, confucius


APP_NAME = os.environ.get('APP_NAME', 'isearch')


def load_app_settings():
    prefix = 'intranet/search/settings/app_settings'
    return confucius.load(f'{prefix}/settings.default.yaml',
                          f'{prefix}/settings.{APP_NAME}.yaml',
                          classes={'Endpoint': entities.Endpoint})


ISEARCH = load_app_settings()


def get_logging_config(conf=ISEARCH['logging']):
    """ В переменных окружения задается конфиг вида:
            handlers.logstash.level:ERROR;root.level:INFO
    """
    env_logging = os.environ.get('ISEARCH_LOGGING', '')
    if not env_logging:
        return conf

    # парсим env_conf в словарь
    env_conf = {}
    for setting in env_logging.split(';'):
        path, value = setting.split(':', 1)
        parts = path.split('.')
        tmp = env_conf
        for i, part in enumerate(parts):
            if i == len(parts) - 1:
                tmp[part] = value
            else:
                tmp.setdefault(part, {})
                tmp = tmp[part]

    return confucius.merge(conf, env_conf)
