import copy
import logging


def MergeConfigs(default_config, override_config, warn_new_key=False):
  """Merges the override config into the default config.

  This function will recursively merge two nested dicts.
  The override_config represents overrides to the default_config dict, so any
  leaf key/value pairs which are present in both dicts will take their value
  from the override_config.

  Args:
    default_config: The dict which will have its values overridden.
    override_config: The dict wich contains the overrides.
    warn_new_key: Determines whether we warn the user if the override config
      has a key that the default config did not have.

  Returns:
    A dict containing the values from the default_config merged with those from
    the override_config.
  """
  def _Merge(d1, d2):
    merged_dict = copy.deepcopy(d1)
    for k, v in d2.iteritems():
      if k not in d1:
        merged_dict[k] = copy.deepcopy(v)
        if warn_new_key:
          logging.warning('The key "%s" was not in the default config, '
                          'but was in user overrides. This may indicate '
                          'a typo.' % k)
      elif isinstance(v, dict):
        merged_dict[k] = _Merge(d1[k], v)
      else:
        merged_dict[k] = v
    return merged_dict

  if override_config:
    return _Merge(default_config, override_config)
  else:
    return default_config