"""Affiliate redirect wrapping for the /jump route.

A faithful Python port of the legacy site/jump.cgi `wrap_affiliate` +
`%AFFILIATE` map (2026-06-02). The map is DATA — `data/affiliates.yml` —
so adding / removing / retuning a retailer is a YAML edit + deploy, no
code change. Audit the merchant IDs against the AvantLink active-
commissions list before go-live (see memory avantlink-active-commissions
and jump-cgi-rewrite-cutover-blocker).

Behavior mirrors the legacy script exactly:
  * OPT-IN wrap, NOT an allowlist — an unmatched retailer STILL gets a
    redirect (raw destination + a cosmetic "#arpartsfinder.com" hash),
    never a drop (memory: jump-affiliate-not-allowlist).
  * match by exact company name first, then by `url_match` substring.
  * avantlink -> click.php?tool_type=cl&merchant_id&website_id&ctc&url
  * suffix    -> append a per-retailer tail (direct programs).
  * avantlink-legacy (mi/pw) -> old integer format, supported as a revert
    path though no retailer currently uses it.
"""
from pathlib import Path
from urllib.parse import quote

import yaml

_PATH = Path(__file__).resolve().parent.parent / "data" / "affiliates.yml"
_DEFAULT_HOME = "https://www.arpartsfinder.com/"
_DEFAULT_AL_BASE = "https://www.avantlink.com/click.php"

_cfg = None


def _load():
    """Parse affiliates.yml once, cache in-process (same pattern as
    changelog.py). Falls back to safe defaults if a key is absent so a
    malformed file can't take down the redirect."""
    global _cfg
    if _cfg is None:
        raw = yaml.safe_load(_PATH.read_text()) or {}
        al = raw.get("avantlink") or {}
        _cfg = {
            "homepage": raw.get("homepage", _DEFAULT_HOME),
            "al_base": al.get("base", _DEFAULT_AL_BASE),
            "al_wid": str(al.get("website_id", "")),
            "retailers": raw.get("retailers") or [],
        }
    return _cfg


def homepage() -> str:
    return _load()["homepage"]


def _find_rule(company: str, url: str):
    retailers = _load()["retailers"]
    # 1) authoritative: exact company-name match
    for r in retailers:
        if r.get("company") == company:
            return r
    # 2) fallback: url_match substring scan
    for r in retailers:
        m = r.get("url_match")
        if m and m in url:
            return r
    return None


def _cosmetic(url: str) -> str:
    """Append the cosmetic '#arpartsfinder.com' attribution hash — but ONLY when
    the URL has no fragment of its own. A retailer that deep-links to a product
    via a URL fragment (#anchor) would get a broken double-fragment from a second
    '#', landing the click on the wrong page. None do today (all AR retailers use
    real product URLs), but the guard keeps it safe. See the ammo site, where
    Ammo.com's #product-anchor URLs hit exactly this."""
    return url if "#" in url else url + "#arpartsfinder.com"


def wrap_affiliate(company: str, url: str, click_id) -> str:
    """Return the final redirect target for a destination `url` belonging
    to `company`, click-tracked as `click_id`. Never raises."""
    cfg = _load()
    rule = _find_rule(company or "", url or "")

    # no match: cosmetic-hash fallback (still redirects)
    if not rule:
        return _cosmetic(url)

    t = rule.get("type")
    if t == "avantlink":
        return (
            cfg["al_base"]
            + "?tool_type=cl"
            + "&merchant_id=" + str(rule.get("mid", ""))
            + "&website_id=" + cfg["al_wid"]
            + "&ctc=" + str(click_id)
            + "&url=" + quote(url, safe="")
        )
    if t == "suffix":
        return url + str(rule.get("tail", ""))
    if t == "avantlink-legacy":
        return (
            "http://www.avantlink.com/click.php"
            + "?tt=cl"
            + "&mi=" + str(rule.get("mi", ""))
            + "&pw=" + str(rule.get("pw", ""))
            + "&ctc=" + str(click_id)
            + "&url=" + quote(url, safe="")
        )
    # unknown type -> hash fallback rather than a broken URL
    return _cosmetic(url)
