import sys
from copy import deepcopy

import yaml


def is_dict(x):
    return callable(getattr(x, 'keys', None))


def is_list(x):
    return callable(getattr(x, 'append', None))


def merge(a, b):
    c = deepcopy(a)

    for key in b.keys():
        if is_dict(b[key]):
            if {'$replace'} == set(b[key].keys()):
                c[key] = b[key]['$replace']
            elif {'$append'} == set(b[key].keys()):
                c[key].append(b[key]['$append'])
            elif is_dict(c.get(key)):
                if '$delete' in b[key]:
                    for subkey in b[key]['$delete']:
                        del c[key][subkey]
                    del b[key]['$delete']
                c[key] = merge(c[key], b[key])
            else:
                c[key] = b[key]
        else:
            c[key] = b[key]

    return c


if __name__ == '__main__':
    filename_a, filename_b = sys.argv[1:]
    with open(filename_a) as file_a:
        with open(filename_b) as file_b:
            a = yaml.unsafe_load(file_a)
            b = yaml.unsafe_load(file_b)
            c = merge(a, b)
            print(yaml.dump(c))
