import ipaddress
import six


def is_valid_ip(project_config, ip_address):
    """
    Verify that an IP address is not being blacklisted
    for the given project.
    """
    blacklist = project_config.config.get('blacklisted_ips')
    if not blacklist:
        return True

    for addr in blacklist:
        # We want to error fast if it's an exact match
        if ip_address == addr:
            return False

        # Check to make sure it's actually a range before
        try:
            if '/' in addr and (
                ipaddress.ip_address(six.text_type(ip_address)) in ipaddress.ip_network(
                    six.text_type(addr), strict=False
                )
            ):
                return False
        except ValueError:
            # Ignore invalid values here
            pass

    return True