"""Datacenter (cloud) IP detection for the /jump affiliate redirect.

botcheck.is_bot catches *declared* crawlers by User-Agent but, by design, can't
catch scrapers wearing a real-browser UA. Those run from rented cloud instances
(observed 2026-06-21: six Google Cloud IPs drove a ~5x traffic spike, mostly
/jump hits, with rotating Chrome/Mac UAs). This module flags such origins by IP
so the /jump route forwards them to the raw URL with NO click tally and NO
affiliate wrap, same as a declared bot.

Ranges come from the providers' own published lists (GCP + AWS), bundled at
data/datacenter_cidrs.txt by scripts/refresh-datacenter-cidrs.py. The web app
NEVER fetches at runtime -- it only reads the bundled file once at import.

Matching is bucketed by IPv4 first-octet so a lookup tests only the handful of
ranges sharing that octet (the file has thousands of CIDRs; a flat scan per
redirect would be wasteful). IPv6 ranges are far fewer and checked linearly.
A missing/unreadable file -> empty tables -> is_datacenter() always False, so a
data problem can never break the redirect (fails open to today's behavior).
"""
import ipaddress
import os

_DATA = os.path.join(os.path.dirname(__file__), "data", "datacenter_cidrs.txt")

# IPv4: {first_octet: [ip_network, ...]}.  IPv6: flat [ip_network, ...].
_V4: dict[int, list] = {}
_V6: list = []


def _load(path: str = _DATA) -> int:
    """Populate the lookup tables from the CIDR file. Returns the count loaded.
    Best-effort: any error leaves the tables as-is (empty on first load)."""
    v4: dict[int, list] = {}
    v6: list = []
    n = 0
    try:
        with open(path) as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith("#"):
                    continue
                try:
                    net = ipaddress.ip_network(line, strict=False)
                except ValueError:
                    continue
                if net.version == 4:
                    # Spread across every /8 the network touches (almost always
                    # one, since cloud ranges are /16 or smaller).
                    start = int(net.network_address) >> 24
                    end = int(net.broadcast_address) >> 24
                    for octet in range(start, end + 1):
                        v4.setdefault(octet, []).append(net)
                else:
                    v6.append(net)
                n += 1
    except OSError:
        return 0
    _V4.clear(); _V4.update(v4)
    _V6.clear(); _V6.extend(v6)
    return n


def is_datacenter(ip: str) -> bool:
    """True if `ip` falls in a bundled cloud-provider range. Unparseable or
    empty input (e.g. 'unknown', a hostname, a spoofed value) -> False."""
    if not ip:
        return False
    try:
        addr = ipaddress.ip_address(ip.strip())
    except ValueError:
        return False
    if addr.version == 4:
        nets = _V4.get(int(addr) >> 24)
        if not nets:
            return False
        return any(addr in net for net in nets)
    return any(addr in net for net in _V6)


def loaded_count() -> int:
    """Total CIDRs currently loaded (for diagnostics/tests)."""
    return sum(len(v) for v in _V4.values()) + len(_V6)


# Load once at import. If the file is missing the tables stay empty and
# is_datacenter() is a harmless constant-False.
_load()
