"""Admit only the created bridge's own expected host routes during network readback."""
import ipaddress

from network_runtime import NetworkFailure


def expected_host_records(subnet, gateway):
    """Exact kernel/address records of an ordinary IPv4 bridge, without a device exemption."""
    selected = ipaddress.IPv4Network(subnet)
    gateway = str(ipaddress.IPv4Network(gateway))
    broadcast = str(selected.broadcast_address) + '/32'
    first = str(selected.network_address) + '/32'
    expected = {'route_connected': {subnet}, 'route_local': {gateway},
                'route_broadcast': {first, broadcast}, 'address_network': {subnet},
                'address_local': {gateway}, 'address_broadcast': {broadcast}}
    for kind in ('route_connected_source', 'route_local_source', 'route_broadcast_source'):
        expected[kind] = {gateway}
    return expected


def verify_host_overlap(inventory, created, subnet):
    selected = ipaddress.IPv4Network(subnet)
    records = inventory.get('host_records', [])
    if set(inventory.get('host_excluded', [])) - {row['subnet'] for row in records}:
        raise NetworkFailure('created_network_overlap')
    expected = expected_host_records(subnet, created['IPAM']['Config'][0]['Gateway'])
    bridge = 'br-' + created['Id'][:12]
    for row in records:
        if selected.overlaps(ipaddress.IPv4Network(row['subnet'])):
            if row['device'] != bridge or row['subnet'] not in expected.get(row['kind'], set()):
                raise NetworkFailure('created_network_overlap')
