import collections


def _serialize_allocations_for_consumer(context, allocations, want_version):
    """Turn a list of allocations into a dict by resource provider uuid.

    {
        'allocations': {
            RP_UUID_1: {
                'generation': GENERATION,
                'resources': {
                    'DISK_GB': 4,
                    'VCPU': 2
                }
            },
            RP_UUID_2: {
                'generation': GENERATION,
                'resources': {
                    'DISK_GB': 6,
                    'VCPU': 3
                }
            }
        },
        # project_id and user_id are added with microverion 1.12
        'project_id': PROJECT_ID,
        'user_id': USER_ID,
        # Generation for consumer >= 1.28
        'consumer_generation': 1
        # Consumer Type for consumer >= 1.38
        'consumer_type': INSTANCE
    }
    """
    allocation_data = collections.defaultdict(dict)
    for allocation in allocations:
        key = allocation.resource_provider.uuid
        if 'resources' not in allocation_data[key]:
            allocation_data[key]['resources'] = {}

        resource_class = allocation.resource_class
        allocation_data[key]['resources'][resource_class] = allocation.used
        generation = allocation.resource_provider.generation
        allocation_data[key]['generation'] = generation

    result = {'allocations': allocation_data}
    if allocations and want_version.matches((1, 12)):
        # We're looking at a list of allocations by consumer id so project and
        # user are consistent across the list
        consumer = allocations[0].consumer
        project_id = consumer.project.external_id
        user_id = consumer.user.external_id
        result['project_id'] = project_id
        result['user_id'] = user_id
        show_consumer_gen = want_version.matches((1, 28))
        if show_consumer_gen:
            result['consumer_generation'] = consumer.generation
        show_consumer_type = want_version.matches((1, 38))
        if show_consumer_type:
            con_name = context.ct_cache.string_from_id(
                consumer.consumer_type_id)
            result['consumer_type'] = con_name

    return result