"""Affiliate click-through redirect — the site-ng port of legacy jump.cgi.

Canonical path is `/jump?site=<parts.id>`; `/jump.cgi?site=<id>` is kept
as a backward-compat alias for links already in the wild (emails, social,
search-indexed, the legacy site's emitted links). This removes site-ng's
dependency on the legacy Perl CGI + its Apache CGI handler, which vanish
at prod cutover. See memory: jump-cgi-rewrite-cutover-blocker.

Flow mirrors the legacy script:
  site=<numeric id>
    -> SELECT url, company FROM parts WHERE id=? AND hidden=0
    -> log the click to jump_log (count+1 per url/day)
    -> affiliate-wrap the destination
    -> 302 redirect
A non-numeric/missing id, no matching row, or a non-http(s) destination
all soft-redirect to the homepage. A DB hiccup fails safe to the homepage
rather than erroring; a jump_log write failure never breaks the redirect.
"""
import logging

from flask import Blueprint, redirect, request

from ..affiliates import homepage, wrap_affiliate
from ..botcheck import is_bot
from ..datacenter import is_datacenter
from ..db import get_db

logger = logging.getLogger(__name__)

bp = Blueprint("jump", __name__)


def _home():
    return redirect(homepage(), code=302)


@bp.route("/jump")
@bp.route("/jump.cgi")
def jump():
    # `site` is the parts id. Digits-only, like the legacy script — the
    # value is interpolated into the affiliate ctc= and bound into SQL.
    site = request.args.get("site", "")
    if not site.isdigit():
        return _home()

    try:
        db = get_db()
        with db.cursor() as cur:
            cur.execute(
                "SELECT url, company FROM parts WHERE id=%s AND hidden=0",
                (site,),
            )
            row = cur.fetchone()
    except Exception:
        logger.exception("jump: parts lookup failed (site=%s)", site)
        return _home()

    if not row or not row.get("url") or not row.get("company"):
        # numeric id but no live row (deleted / hidden / stale link)
        return _home()

    dest = row["url"]
    company = row["company"]

    # Safety floor: only ever 302 to http(s). Stops a junk row slipping a
    # javascript:/data: URL into the redirect. parts.url is scanner-written
    # so the realistic surface is ~zero, but this is a cheap floor.
    if not dest.lower().startswith(("http://", "https://")):
        return _home()

    # Bots -> forward to the UNTOUCHED real URL: no click tally, no affiliate
    # wrap. They have no purchase intent, so routing them through AvantLink is
    # invalid affiliate traffic and counting them pollutes the click metrics.
    # They still reach the real product (a clean 302), we just don't credit or
    # log it. Two gates:
    #   - is_bot: DECLARED crawlers by User-Agent (Applebot, Meta, AI/SEO). See
    #     botcheck.py.
    #   - is_datacenter: scrapers wearing a real-browser UA but originating from
    #     a cloud provider (GCP/AWS) — the UA gate can't catch these. Scan the
    #     whole forwarded chain (+ remote_addr) so a cloud IP anywhere in it
    #     trips the gate, regardless of hop count. See datacenter.py.
    ua = request.headers.get("User-Agent", "")
    chain = list(request.access_route) + [request.remote_addr or ""]
    if is_bot(ua) or any(is_datacenter(ip) for ip in chain):
        return redirect(dest, code=302)

    # Click tally (feeds /instock/popular + ops metrics). MUST NOT break
    # the user-facing redirect on a write failure.
    try:
        with db.cursor() as cur:
            cur.execute(
                "INSERT INTO jump_log (company, url, count, day) "
                "VALUES (%s, %s, 1, CURDATE()) "
                "ON DUPLICATE KEY UPDATE count = count + 1",
                (company, dest),
            )
    except Exception:
        logger.exception("jump: jump_log write failed (site=%s)", site)

    return redirect(wrap_affiliate(company, dest, site), code=302)
