from typing import OrderedDict


def order_extensions_grouped_by_priority(extensions):
    """
    Group the extensions based on their `PRIORITY` attribute.

    Each priority group is ordered by the entry point name.

    :param extensions: a dict mapping the entry point name to the
      extension instance
    :returns: ordered dict mapping the priority to an ordered dict which maps
      the entry point name to the extension instance
    """
    # use negative priority and inverted reverse flag
    # to get highest priorities first and
    # extensions withing the same priority group in alphabetical order
    ordered_extensions = OrderedDict(
        sorted(
            extensions.items(),
            key=lambda pair: (-pair[1].PRIORITY, pair[0])))
    grouped_extensions = OrderedDict()
    for name, extension in ordered_extensions.items():
        priority = extension.PRIORITY
        if priority not in grouped_extensions:
            grouped_extensions[priority] = OrderedDict()
        grouped_extensions[priority][name] = extension
    return grouped_extensions