from pathlib import Path
from dotenv import load_dotenv
import yaml

# ################################################################################
# config_load
# ################################################################################

def find_yml(name):
    p = Path(f'./{name}')
    if p.exists(): return p
    p = Path(f'/run/secrets/{name}')
    if p.exists(): return p
    return None

def config_load(name=None):
    """ Load config yml file. File name default is f'config-{name}.yml' or config.yml by default.
        Checks for file first in the current dir then in /run/secrets """
    load_dotenv()
    name = 'config.yml' if name is None else f'config-{name}.yml'
    fname = find_yml(name)
    if fname is None:
        raise RuntimeError('Unable to find config file')
    with open(str(fname),'r') as stream:
        try:
            cfg = yaml.safe_load(stream)
        except yaml.YAMLError as err:
            raise RuntimeError(f'Unable to load config file: {str(err)}')
    return cfg
