import collections


def build_node_statistics(nodes, images):
    """Build a dictionary of cache statistics about a group of nodes."""
    # Generic statistics applicable to all groups of nodes.
    node_statistics = {
        'provisioned': len(list(filter(lambda n: n.provisioned, nodes))),
        'not provisioned': len(list(filter(lambda n: not n.provisioned,
                                           nodes))),
        'available (not cached)': len(list(filter(lambda n: n.can_cache(),
                                                  nodes))),
        'cached (includes \'caching\')':
            len(list(filter(lambda n: n.cached and not n.provisioned, nodes))),
        'total': len(nodes),
        'images': collections.defaultdict(lambda: 0)
    }

    image_names_by_uuid = {image.uuid: image.name for image in images}

    # Build statistics around which images are cached.
    for node in nodes:
        if (node.cached and
                not node.provisioned and
                node.cached_image_uuid is not None):
            # If we don't know the name of the image, just return the UUID.
            image_name = image_names_by_uuid.get(node.cached_image_uuid,
                                                 node.cached_image_uuid)
            node_statistics['images'][image_name] += 1

    return node_statistics