from collections import defaultdict
import netaddr


def build_reverse_mappings_from_anm_input(anm):
    """Builds reverse mappings from ANM input graph,
    assumes addresses have already been allocated onto input graph,
    either externally or by previous run"""


    g_in = anm['input']
    rev_map = {
            "loopbacks": {},
            "infra_interfaces": {},
            "subnets": {},
    }

    subnets = defaultdict(list)

    for node in g_in:
        rev_map["loopbacks"][str(node.loopback_v4)] = node
        for interface in node.physical_interfaces:
            rev_map["infra_interfaces"][str(interface.ipv4_address)] = interface

            prefixlen = interface.ipv4_prefixlen
            cidr_string = "%s/%s" % (interface.ipv4_address, prefixlen)
            intermediate_subnet = netaddr.IPNetwork(cidr_string)
            subnet_cidr_string = "%s/%s" % (intermediate_subnet.network, prefixlen)
            subnet = netaddr.IPNetwork(subnet_cidr_string)
            subnets[subnet].append(interface)

    for subnet, interfaces in subnets.items():
        subnet_str = str(subnet)
        rev_map['subnets'][subnet_str] = "_".join(str(i.node) for i in interfaces)

    return rev_map