"""Unit tests for ngsite.datacenter.is_datacenter — the cloud-origin filter that
lets /jump treat real-UA scrapers running on GCP/AWS the same as declared bots
(no affiliate wrap, no click tally). Complements botcheck.is_bot, which only
catches declared-by-UA crawlers. See memory: jump-bot-filter.

The CIDR table is the bundled data/datacenter_cidrs.txt (refreshed by
scripts/refresh-datacenter-cidrs.py). These assert behavior against ranges that
are stable parts of GCP/AWS allocations; if a refresh ever drops one, that's a
signal worth seeing.
"""
import ipaddress

import pytest

from ngsite import datacenter


# The six Google Cloud IPs from the 2026-06-21 traffic spike (all resolve to
# *.bc.googleusercontent.com).
SPIKE_GCP_IPS = [
    "8.231.32.216", "35.254.236.153", "34.153.25.73",
    "34.170.181.56", "34.122.206.137", "34.162.69.53",
]

NON_DATACENTER = [
    "8.8.8.8",        # Google Public DNS — a service IP, not a compute range
    "1.1.1.1",        # Cloudflare DNS
    "98.51.23.10",    # residential-style
    "73.162.4.55",    # residential-style (Comcast space)
]

JUNK = ["", "unknown", "not-an-ip", "999.1.1.1", "::-bad", None]


def test_table_loaded():
    # The bundled file must actually be present + parsed; a 0 count would mean
    # the filter silently does nothing.
    assert datacenter.loaded_count() > 1000


@pytest.mark.parametrize("ip", SPIKE_GCP_IPS)
def test_spike_gcp_ips_flagged(ip):
    assert datacenter.is_datacenter(ip) is True


def test_aws_range_flagged():
    # Pick a live AWS prefix straight from the loaded table and test an address
    # inside it (robust to AWS reallocating any single block).
    aws_like = None
    for nets in datacenter._V4.values():
        for net in nets:
            if net.version == 4 and net.prefixlen <= 24:
                aws_like = net
                break
        if aws_like:
            break
    assert aws_like is not None
    inside = str(list(aws_like.hosts())[0]) if aws_like.num_addresses > 2 \
        else str(aws_like.network_address)
    assert datacenter.is_datacenter(inside) is True


@pytest.mark.parametrize("ip", NON_DATACENTER)
def test_non_datacenter_not_flagged(ip):
    assert datacenter.is_datacenter(ip) is False


@pytest.mark.parametrize("ip", JUNK)
def test_junk_inputs_safe(ip):
    # Never raise; unparseable/empty -> False (the redirect must never break).
    assert datacenter.is_datacenter(ip) is False


def test_fails_open_when_empty():
    # Empty tables (the state at import if the file were missing) -> always
    # False, so a data problem degrades to today's behavior, never an error.
    # Also: a failed reload returns 0 and is non-raising (and, by design,
    # preserves whatever was already loaded rather than wiping it).
    saved_v4, saved_v6 = dict(datacenter._V4), list(datacenter._V6)
    try:
        datacenter._V4.clear()
        datacenter._V6.clear()
        assert datacenter.is_datacenter("34.153.25.73") is False
        assert datacenter._load("/no/such/datacenter/file.txt") == 0  # no raise
        assert datacenter.is_datacenter("34.153.25.73") is False
    finally:
        datacenter._V4.clear(); datacenter._V4.update(saved_v4)
        datacenter._V6.clear(); datacenter._V6.extend(saved_v6)
    assert datacenter.is_datacenter("34.153.25.73") is True  # table restored
