"""Cross-merchant same-product matching for the /p/ product page (v1, live).

Given a product, find OTHER merchants carrying the SAME physical product from
our OWN `parts` table (no external search) — title-driven fuzzy match within the
same `type`. Precision-FIRST: a wrong "cheaper elsewhere" match is worse than a
missing one, so we bias hard to precision and return two tiers (confident +
possible). Full design: docs/product-match-comparison.md.

v1 is pure-Python scoring over the same-type in-stock pool (a few hundred rows),
cached per product — no FULLTEXT / DDL / new schema. Limited to low-variant
types (SAFE_TYPES) where the title fully identifies the item; barrels/uppers are
HELD until length/caliber attribute extraction exists (16" vs 18" of one model
are different products and would need attrs to tell apart).
"""
import re

# Types whose title fully identifies the item (low variant risk). v1 launch set.
SAFE_TYPES = {"bcg", "ch", "trigger", "muzzle"}

# Manufacturer brands that appear in / get prepended to titles. Used two ways:
# (1) a SHARED brand is a positive signal; (2) brand tokens are dropped from the
# generic token overlap so a title that includes the brand isn't penalized
# against one that omits it (the manufacturer-direct prepend asymmetry). Static
# for v1 — derive from the scanner brand_prefix configs later. Lowercase; multi-
# word entries matched as phrases before tokenizing.
_BRANDS = [
    "angstadt arms", "aero precision", "ballistic advantage", "bravo company",
    "bear creek arsenal", "daniel defense", "strike industries", "primary arms",
    "palmetto state armory", "rainier arms", "san tan tactical", "toolcraft",
    "fail zero", "failzero", "young manufacturing", "sionics", "sons of liberty",
    "geissele", "radian", "cmmg", "faxon", "kak industry", "bcm", "lmt", "lantac",
    "jp enterprises", "wmd", "2a armament", "andro corp", "apf armory",
    "american built arms", "a b arms", "anarchy outdoors", "magpul", "silencerco",
    "surefire", "dead air", "griffin armament", "yankee hill", "precision reflex",
    "v seven", "v7", "seekins", "odin works", "expo arms",
]

# Caliber canonicalization: many spellings -> one token. SAME caliber is a strong
# positive; DIFFERENT caliber is a HARD reject (a 9mm BCG != a 5.56 BCG). Ordered
# most-specific first. .223 and 5.56 collapse to one family (merchants list them
# interchangeably, e.g. ".223/556").
_CALIBERS = [
    (re.compile(r'7\.?62\s*x\s*39'), "cal762x39"),
    (re.compile(r'7\.?62\s*x\s*51|\.308|\b308\b|308\s*win'), "cal308"),
    (re.compile(r'6\.?5\s*(creedmoor|cm|grendel)'), "cal65"),
    (re.compile(r'6\.?8\s*spc'), "cal68"),
    (re.compile(r'300\s*(blk|blackout|aac|ham)'), "cal300blk"),
    (re.compile(r'350\s*legend'), "cal350"),
    (re.compile(r'5\.?56\s*x\s*45|5\.?56|\.223|\b223\b|223\s*wylde'), "cal556"),
    (re.compile(r'\b9\s*mm\b|9\s*x\s*19'), "cal9mm"),
    (re.compile(r'\b10\s*mm\b'), "cal10mm"),
    (re.compile(r'\.45\s*acp|\b45\s*acp\b'), "cal45"),
    (re.compile(r'\b40\s*s\s*&?\s*w\b|\b40\s*sw\b'), "cal40"),
]

# Platform family (AR10/SR25/LR308 vs AR15/M4/M16) — a hard DISCRIMINATOR like
# caliber (an AR10 charging handle is not an AR15 one), NOT a model number.
# Both-present-and-disjoint => reject. Stripped before model/token extraction so
# "ar10"/"sr25" can't masquerade as a distinctive model code.
_PLATFORMS = [
    (re.compile(r'\bar\s*-?\s*10\b|\blr\s*-?\s*308\b|\bsr\s*-?\s*25\b'
                r'|\bar\s*-?\s*308\b|\bdpms\b'), "ar10"),
    (re.compile(r'\bar\s*-?\s*15\b|\bm\s*4\b|\bm\s*16\b'), "ar15"),
]

# Thread pitch (1/2x28, 5/8x24, 9/16x24, 3/4x24, M18x1.0, .578x28) — a common
# SPEC shared by many DIFFERENT muzzle devices, NOT a model number. Stripped
# before model/token extraction so it can't masquerade as a distinctive code.
_THREAD_RE = re.compile(
    r'\b\d{1,2}\s*/\s*\d{1,2}\s*x\s*\d{2}(\.\d+)?\b|\bm\d{2}\s*x\s*[\d.]+\b'
    r'|\b\.?\d{3}\s*x\s*\d{2}\b')

# Model-number-ish token: >=4 chars, contains BOTH a letter and a digit
# (AA56BC, DDM4V7, AA09BCGNIT). A SHARED one is near-unique = strong match; two
# DIFFERENT ones = strong signal they're different products.
_MODEL_RE = re.compile(r'\b(?=[a-z0-9]*[a-z])(?=[a-z0-9]*\d)[a-z0-9]{4,}\b')

# Generic words that carry no discriminating signal for these types.
_STOP = {
    "the", "a", "an", "for", "with", "and", "of", "in", "to", "black", "nitride",
    "phosphate", "finish", "assembly", "group", "carrier", "bolt", "complete",
    "ar", "ar15", "ar10", "m16", "m4", "rifle", "pistol", "kit", "new", "gen",
    "mil", "spec", "milspec", "nato", "type", "style", "device", "muzzle",
    "trigger", "charging", "handle", "bcg", "inc", "llc", "co", "usa",
}


def _canon_calibers(text):
    found = set()
    for rx, tok in _CALIBERS:
        if rx.search(text):
            found.add(tok)
    # 5.56/.223 and .308 both name a bore; keep distinct tokens but treat the
    # 556 family as one (already collapsed above).
    return found


def _prep(title):
    """Return (tokens, calibers, models, brands, platforms) for a title."""
    t = " " + (title or "").lower() + " "
    cals = _canon_calibers(t)
    plats = {tok for rx, tok in _PLATFORMS if rx.search(t)}
    brands = {b for b in _BRANDS if b in t}
    # strip brand phrases + caliber + platform + thread pitch so none pollute the
    # generic tokens or get mistaken for a distinctive model number
    for b in brands:
        t = t.replace(b, " ")
    for rx, _tok in _CALIBERS:
        t = rx.sub(" ", t)
    for rx, _tok in _PLATFORMS:
        t = rx.sub(" ", t)
    t = _THREAD_RE.sub(" ", t)
    words = re.findall(r"[a-z0-9]+", t)
    models = {w for w in words if _MODEL_RE.match(w)}
    tokens = {w for w in words if w not in _STOP and len(w) > 1 and w not in models}
    return tokens, cals, models, brands, plats


# Tier thresholds (0..100). Tuned against real BCG/CH/trigger/muzzle data.
_CONFIDENT = 82
_POSSIBLE = 60


def _score(a, b):
    """a, b = (tokens, cals, models, brands). Returns (score, reason).

    BRAND is the anchor: the same physical product across merchants shares its
    manufacturer, so two DIFFERENT identifiable brands => different product
    (reject). Caliber + model number are the within-brand discriminators. This
    is what keeps 'APF BCG' from matching 'KAK BCG' (precision-first)."""
    at, ac, am, ab, ap = a
    bt, bc, bm, bb, bp = b
    # HARD rejects (precision guards)
    if ac and bc and not (ac & bc):
        return 0, "caliber-conflict"
    if ap and bp and not (ap & bp):
        return 0, "platform-conflict"
    if am and bm and not (am & bm):
        return 0, "model-conflict"
    if ab and bb and not (ab & bb):
        return 0, "brand-conflict"
    shared_model = bool(am and (am & bm))
    shared_brand = bool(ab & bb)
    shared_cal = bool((ac & bc) or (ap & bp))       # caliber OR platform agree
    inter, union = at & bt, at | bt
    jacc = len(inter) / len(union) if union else 0.0
    overlap = len(inter) / min(len(at), len(bt)) if at and bt else 0.0
    tok = 100 * (0.45 * jacc + 0.55 * overlap)
    if shared_model:                                  # near-unique -> confident
        score = 92
    elif shared_brand:
        # Same brand, but the same brand makes MANY products, so lean on the
        # remaining tokens + caliber to tell models apart (a Geissele trigger
        # GUARD must not match a Geissele G2S trigger). Brand+caliber alone
        # floors at "possible" for the caliber-bearing types (BCG/muzzle) where
        # the title is often just "<brand> <caliber> BCG"; different models with
        # distinct name tokens stay low and drop out.
        score = 30 + 0.60 * tok + (30 if shared_cal else 0)
    else:
        # No brand anchor (neither title names a listed brand). Fall back to
        # token/caliber similarity only, and cap BELOW confident — without a
        # brand we can't be sure, so this is "possible" at best.
        score = min(_CONFIDENT - 1, 0.85 * tok + (6 if shared_cal else 0))
    return min(100.0, score), "ok"


def find_matches(rows, target, max_per_tier=6):
    """rows = list of same-type in-stock candidate dicts (id, company,
    description, price, url, img) INCLUDING the target; target = the product dict.
    Returns {"confident": [...], "possible": [...]} of merchant dicts, one
    (cheapest) per company, excluding the target's own company. Pure/testable."""
    if (target.get("type") or "") not in SAFE_TYPES:
        return {"confident": [], "possible": []}
    tprep = _prep(target.get("description"))
    tcompany = target.get("company")
    scored = []
    for r in rows:
        if r["id"] == target["id"] or r.get("company") == tcompany:
            continue
        if not (r.get("description") or "").strip() or not r.get("price"):
            continue
        s, why = _score(tprep, _prep(r["description"]))
        if s >= _POSSIBLE:
            scored.append((s, r))
    # cheapest listing per company, keep its best score
    best = {}
    for s, r in scored:
        c = r.get("company")
        if c not in best or float(r["price"]) < float(best[c][1]["price"]):
            best[c] = (s, r)
    ranked = sorted(best.values(), key=lambda sr: (-sr[0], float(sr[1]["price"])))
    out = {"confident": [], "possible": []}
    for s, r in ranked:
        tier = "confident" if s >= _CONFIDENT else "possible"
        if len(out[tier]) >= max_per_tier:
            continue
        out[tier].append({
            "id": r["id"], "company": r["company"],
            "description": r["description"], "price": float(r["price"]),
            "url": r.get("url"), "img": r.get("img"), "score": round(s),
        })
    return out
