import six
import itertools
import operator


def merge_practices(*args, **kwargs):
  """Merge two or more dictionaries, preferring values in increasing order of index in `order`.

  Treats practices with no `status` as 'na'.
  """
  order = kwargs.pop('order', ['unknown', 'na', 'nudge', 'warn', 'ok'])
  if len(kwargs) > 0:
    raise TypeError("merge_practices() got unexpected keyword argument(s) {:s}"
                    "".format(', '.join("'{:s}'".format(kw) for kw in six.iterkeys(kwargs))))

  practices = dict()
  for practice in set(itertools.chain.from_iterable(arg.keys() for arg in args)):
    practices[practice] = max(
        (arg.get(practice, {'status': 'unknown'}) for arg in args),
        key=lambda _practice: operator.indexOf(order, _practice.get('status', 'unknown'))
    )
  return practices