from typing import OrderedDict


def enumerate_fields(_, publication):
    """Flattens all currently published fields.

    By default, publications are deeply nested dict structures. This can be very hard to read
    when rendered in certain outputs. PagerDuty is one example where the default UI does a very
    poor job rendering nested dicts.

    This publisher collapses deeply nested fields into a single-leveled dict with keys that
    correspond to the original path of each value in a deeply nested dict. For example:

    {
      "top1": {
        "mid1": "low",
        "mid2": [ "low1", "low2", "low3" ],
        "mid3": {
          "low1": "verylow"
        }
      },
      "top2": "mid"
    }

    .. would collapse into the following structure:

    {
      "top1.mid1": "low",
      "top1.mid2[0]": "low1",
      "top1.mid2[1]": "low1",
      "top1.mid2[2]": "low1",
      "top1.mid3.low1: "verylow",
      "top2": "mid"
    }

    The output dict is an OrderedDict with keys sorted in alphabetical order.
    """
    def _recursive_enumerate_fields(structure, output_reference, path=''):
        if isinstance(structure, list):
            for index, item in enumerate(structure):
                _recursive_enumerate_fields(item, output_reference, '{}[{}]'.format(path, index))

        elif isinstance(structure, dict):
            for key in structure:
                _recursive_enumerate_fields(structure[key], output_reference, '{prefix}{key}'.format(
                    prefix='{}.'.format(path) if path else '',  # Omit first period
                    key=key
                ))

        else:
            output_reference[path] = structure

    output = {}
    _recursive_enumerate_fields(publication, output)

    return OrderedDict(sorted(output.items()))