"""Integration: /jump forwards cloud-origin (datacenter) traffic to the RAW
retailer URL — no affiliate wrap, no jump_log tally — even when the User-Agent
is a real browser. This is the gate botcheck (UA-only) can't provide. Driven via
X-Forwarded-For so we exercise the real request.access_route reading.
See memory: jump-bot-filter.
"""
import pytest

# A Google Cloud IP from the 2026-06-21 spike; a stable GCP allocation.
GCP_IP = "34.153.25.73"
REAL_BROWSER = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
                "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0 Safari/537.36")


@pytest.fixture()
def a_part(db_conn):
    """One in-stock part with an http(s) url + company, for /jump?site=<id>."""
    with db_conn.cursor() as cur:
        cur.execute(
            "SELECT id, url, company FROM parts "
            "WHERE instock=1 AND (hidden IS NULL OR hidden=0) "
            "  AND url LIKE 'http%' AND company <> '' ORDER BY id LIMIT 1")
        row = cur.fetchone()
    if not row:
        pytest.skip("need an in-stock part with a url in the dev mirror")
    return row


def test_datacenter_ip_forwards_to_raw_url(client, a_part):
    # Real-browser UA but a cloud IP -> the new datacenter gate fires: a 302
    # straight to the untouched destination (no affiliate ctc=, no log).
    r = client.get("/jump?site=%s" % a_part["id"],
                   headers={"User-Agent": REAL_BROWSER,
                            "X-Forwarded-For": GCP_IP})
    assert r.status_code == 302
    assert r.headers["Location"] == a_part["url"]


def test_datacenter_ip_anywhere_in_chain_trips(client, a_part):
    # A cloud hop preceding a residential one in the forwarded chain still trips
    # the gate (we scan the whole chain, not just one end).
    r = client.get("/jump?site=%s" % a_part["id"],
                   headers={"User-Agent": REAL_BROWSER,
                            "X-Forwarded-For": "%s, 73.162.4.55" % GCP_IP})
    assert r.status_code == 302
    assert r.headers["Location"] == a_part["url"]
