import os
import yaml
import collections


def load_config(path: str, domain_name: str = None):
    with open(path) as f:
        config = yaml.load(f, Loader=yaml.FullLoader)
    
    params = config['planner']
    # overridings
    if domain_name in config.keys():
        override_dict(params, config[domain_name])
    return {'planner': params}


def override_dict(d1, d2):
    for k, v in d2.items():
        if isinstance(v, collections.abc.Mapping):
            d1[k] = override_dict(d1.get(k, {}), v)
        else:
            d1[k] = v
    return d1


def save_config(path: str, config):
    with open(os.path.join(path, 'config.yml'), 'w+') as f:
        yaml.dump(config, f, default_flow_style=False)
