"""Build compatibility checker (v1).

Inspects a list of build line-items and surfaces likely cross-part
mismatches — e.g., a .308 mag with a 5.56 barrel, or a 9mm magwell
lower paired with a 5.56 upper. Non-blocking: the user can still
save and share the build. The warning is informational ("you might
want to double-check before buying"), not a hard error — our
detection is heuristic and the user might be doing something
deliberate.

Approach: pattern matching against `parts.description` per part
type. We don't have structured attribute columns on `parts` today;
v1 reads them out of the description text using regex. Same shape
as the existing hide-rule / reclassify-rule pattern engines.

v2 (deferred, see TODO.md): hand-curated `parts_attrs` table with
a dashboard reviewer tab once these rules have surfaced enough
mis-tags to be worth manual cleanup.

Conservative by design:
- Patterns require WORD BOUNDARIES so "9mm" doesn't false-match
  "9mm-shroud" oddity strings (it would; that's fine, but watch).
- If we can't determine a part's caliber/magwell, attrs are None
  and the part participates in no comparisons. Better to under-
  warn than to spam false positives.
- Mismatches fire only between part TYPES that have a real coupling
  (barrel vs mag, lower vs barrel, etc.) — not pairwise across
  every type combo.

Module exports:
- `check_build(lines) -> list[Warning]` — call this from views
- `extract_attrs(line) -> dict` — useful for debugging / future
  curated-attrs table
"""

from __future__ import annotations

import re
from dataclasses import dataclass
from typing import List, Optional


# ── Caliber patterns ─────────────────────────────────────────────
# Each pattern maps a normalized caliber label to a list of regexes
# that match common ways the caliber appears in descriptions.
# Order matters within a single attribute extraction: the FIRST
# match wins, so put the most-specific patterns first. We don't put
# `.22 lr` patterns before `.223` patterns (would conflict) — the
# `.22 lr` pattern requires "lr" / "long rifle" / "22lr" form.

CALIBER_PATTERNS = [
    # ── .308 family (AR-10 magwell) ──────────────────────────
    ('.308', [
        re.compile(r'\b(?:\.?308\s*(?:win)?)\b', re.IGNORECASE),
        re.compile(r'\b7[.\- ]?62\s*x?\s*51\b', re.IGNORECASE),
        re.compile(r'\b7\.62\s*(?:nato|n\.?a\.?t\.?o\.?)\b', re.IGNORECASE),
        re.compile(r'\bm118\s*(?:lr|sr)?\b', re.IGNORECASE),
        re.compile(r'\b7\.62\b', re.IGNORECASE),
    ]),
    # 6.5 Creedmoor — must match before bare 6.5 patterns (none here)
    ('6.5cm', [
        re.compile(r'\b6[.\- ]?5\s*(?:cm|creedmoor|creed)\b', re.IGNORECASE),
    ]),
    # 6mm Creedmoor — must match before 6mm ARC (both start with "6mm")
    ('6mm-cm', [
        re.compile(r'\b6\s*mm\s*(?:cm|creedmoor|creed)\b', re.IGNORECASE),
    ]),
    # .243 Winchester — AR-10-family cartridge
    ('.243', [
        re.compile(r'\b\.?243\s*(?:win)?\b', re.IGNORECASE),
    ]),

    # ── Grendel family (AR-15 magwell, wider case than 5.56) ──
    ('6mm-arc', [
        re.compile(r'\b6\s*mm\s*arc\b', re.IGNORECASE),
        re.compile(r'\b6\s*arc\b', re.IGNORECASE),
    ]),
    ('6.5grendel', [
        re.compile(r'\b6[.\- ]?5\s*grendel\b', re.IGNORECASE),
        re.compile(r'\b6\.5g\b', re.IGNORECASE),
    ]),
    ('.224valk', [
        re.compile(r'\b\.?224\s*valk(?:yrie)?\b', re.IGNORECASE),
    ]),

    # ── 5.56 family (AR-15 magwell, 5.56 case body) ──────────
    # .300 BLK is necked-up from 5.56 brass; same case body, same mags.
    ('.300blk', [
        re.compile(r'\b300\s*(?:blk|aac|blackout|bo|black\s*out)\b', re.IGNORECASE),
        re.compile(r'\b\.300\s*(?:blk|blackout)\b', re.IGNORECASE),
    ]),

    # 6.8 SPC — AR-15 magwell, its own cartridge family (different
    # case body from both 5.56 and Grendel-family). Keep separate.
    ('6.8spc', [
        re.compile(r'\b6[.\- ]?8\s*(?:spc|rem|spec)\b', re.IGNORECASE),
    ]),

    # ── 9mm (AR-9 platform) ───────────────────────────────────
    ('9mm', [
        re.compile(r'\b9\s*mm\b', re.IGNORECASE),
        re.compile(r'\b9\s*x\s*19\b', re.IGNORECASE),
    ]),

    # ── .22 LR ────────────────────────────────────────────────
    ('.22lr', [
        re.compile(r'\b\.?22\s*l\.?r\.?\b', re.IGNORECASE),
        re.compile(r'\b22\s*long\s*rifle\b', re.IGNORECASE),
        re.compile(r'\b22lr\b', re.IGNORECASE),
    ]),

    # ── 5.56 / .223 (must come LAST among AR-15 calibers) ─────
    # ".223" is a short token that could appear in product codes;
    # word boundaries limit it but anything 6mm/6.5 above must be
    # checked first or it'd swallow them.
    ('5.56', [
        re.compile(r'\b5[.\- ]?56\s*(?:nato|x\s*45)?\b', re.IGNORECASE),
        re.compile(r'\b\.?223\s*(?:rem|remington|wylde)?\b', re.IGNORECASE),
    ]),
]


# ── Cartridge-family map ─────────────────────────────────────────
# Two calibers are MAGAZINE-COMPATIBLE only if they're in the same
# cartridge family. Family ≈ "shares case body + feed-lip geometry."
#
# This is stricter than just "same magwell" — 5.56 mags will INSERT
# into a 6mm ARC build's AR-15 magwell, but the wider 6mm ARC case
# body won't feed reliably from 5.56 feed lips. Per Mike's test
# 2026-05-27 + web confirmation: "you cannot use a standard 5.56
# NATO/.223 Remington magazine for a 6mm ARC upper. The 6mm ARC
# cartridge has a wider case body than the 5.56, meaning it will
# not fit properly in standard 5.56/.223 magazine feed lips and
# will cause severe feeding issues."
#
# Family naming: short label good for the warning text + dict keys.
FAMILY_OF = {
    # 5.56 family — AR-15 magwell, narrow case body
    '5.56':       '5.56',
    '.300blk':    '5.56',     # necked-up 5.56 brass; same mag
    # Grendel family — AR-15 magwell, wider case body than 5.56
    '6mm-arc':    'grendel',
    '6.5grendel': 'grendel',
    '.224valk':   'grendel',  # Grendel parent case
    # .308 family — AR-10 magwell
    '.308':       '.308',
    '6.5cm':      '.308',
    '6mm-cm':     '.308',
    '.243':       '.308',
    # 9mm — AR-9 magwell, blowback action
    '9mm':        '9mm',
    # Sub-families that don't fit cleanly with the others:
    '6.8spc':     '6.8spc',   # AR-15 magwell but unique mag/case
    '.22lr':      '.22lr',    # AR-15 magwell but rimfire conversion
}


# Cartridge family → magwell platform. Used for the lower↔upper
# magwell-mismatch check (e.g., AR-9 lower with a 5.56 upper).
FAMILY_PLATFORM = {
    '5.56':    'ar15',
    'grendel': 'ar15',
    '.308':    'ar10',
    '9mm':     'ar9',
    '6.8spc':  'ar15',
    '.22lr':   'ar15',
}


def _family_of(caliber):
    """Look up a caliber's cartridge family. Unknown calibers fall
    back to themselves so the comparison is strict (no two unknown
    calibers are assumed compatible)."""
    if not caliber:
        return None
    return FAMILY_OF.get(caliber, caliber)


# ── Magwell patterns ─────────────────────────────────────────────
# A lower receiver's magwell type determines which mags fit AND
# which upper it can be paired with (.308 magwell upper-lower
# coupling is non-interchangeable with AR-15). Conservative:
# default to None (unknown), not "5.56", so unknown lowers don't
# false-warn against everything.

MAGWELL_PATTERNS = [
    # 9mm / PCC magwell
    ('9mm', [
        re.compile(r'\bar[\- ]?9\b', re.IGNORECASE),
        re.compile(r'\b(?:9\s*mm|9x19)\b', re.IGNORECASE),
        re.compile(r'\bpcc\b', re.IGNORECASE),
        re.compile(r'\bpistol[\- ]?caliber\b', re.IGNORECASE),
        re.compile(r'\bglock\s*mag(?:azine)?s?\b', re.IGNORECASE),
        re.compile(r'\bcolt\s*style\s*9\b', re.IGNORECASE),
    ]),
    # AR-10 / LR-308 magwell
    ('.308', [
        re.compile(r'\b(?:ar[\- ]?10|lr[\- ]?308|sr[\- ]?25|dpms)\b', re.IGNORECASE),
        re.compile(r'\b(?:\.?308|7\.62)\s*(?:lower|receiver)\b', re.IGNORECASE),
    ]),
    # AR-15 / 5.56 magwell — must come LAST since "AR-15" sometimes
    # appears in AR-9 or AR-10 model names (e.g., "AR-15-style
    # ergonomics for the AR-9"). We only call it AR-15-magwell if
    # the other patterns above didn't match.
    ('5.56', [
        re.compile(r'\bar[\- ]?15\b', re.IGNORECASE),
        re.compile(r'\bmil[\- ]?spec\b', re.IGNORECASE),
        re.compile(r'\b(?:5\.56|\.223)\b', re.IGNORECASE),
    ]),
]


# Which part types we attempt to extract WHICH attributes for.
# Empty list = no extraction. We don't attempt magwell on
# upper-receiver / barrel parts (their magwell is implied by
# caliber + the lower they're paired with).
_TYPE_ATTRS = {
    # Caliber-carrying parts
    'mag':           ['caliber'],
    'barrel':        ['caliber'],
    'bcg':           ['caliber'],
    'completeupper': ['caliber'],
    'strippedupper': ['caliber'],
    # Lowers carry a magwell type
    'completelower': ['magwell'],
    'strippedlower': ['magwell'],
    'upperlower':    ['magwell', 'caliber'],   # complete sets
    'lbk':           ['magwell'],              # lower build kit
    'lpk':           ['magwell'],              # lower parts kit
}


@dataclass
class Warning:
    """One compatibility issue. `parts` is the list of build lines
    involved. `field` identifies the attribute that mismatches
    (caliber / magwell). `values` carries the conflicting values."""
    parts: list           # list of line dicts (each with id, type, description, qty)
    field: str            # 'caliber' | 'magwell'
    values: list          # the conflicting values, parallel to `parts`
    message: str          # rendered text for the banner


def _first_match(text: str, patterns) -> Optional[str]:
    """Return the label of the first pattern group that matches the
    text, or None if nothing matches."""
    if not text:
        return None
    for label, regexes in patterns:
        for rx in regexes:
            if rx.search(text):
                return label
    return None


def extract_attrs(line) -> dict:
    """Read out the structured attributes we can detect from a build
    line's description. Returns a dict with the keys this line's
    type would carry (per `_TYPE_ATTRS`), value = string label
    (e.g., '5.56') or None when no pattern matched.

    `line` is a dict with at least `type` and `description`. Tolerates
    missing fields (returns empty dict).
    """
    t = line.get('type') or ''
    desc = line.get('description') or ''
    wants = _TYPE_ATTRS.get(t, [])
    out = {}
    if 'caliber' in wants:
        out['caliber'] = _first_match(desc, CALIBER_PATTERNS)
    if 'magwell' in wants:
        out['magwell'] = _first_match(desc, MAGWELL_PATTERNS)
    return out


# Compatible caliber sets — calibers that are MECHANICALLY
# interchangeable. Example: 5.56 NATO and .223 Remington use the
# same chamber for most rifles; we treat both as '5.56'. .308 Win
# and 7.62 NATO are similarly grouped (we normalize both to '.308'
# in the patterns). 9mm and 9x19 are the same. So in practice
# normalization in CALIBER_PATTERNS already handles this — we just
# compare labels directly.

# Calibers that COULD work in a multi-caliber barrel or magazine
# (e.g., 5.56-chamber barrels can fire .223). The pattern engine
# normalizes both to '5.56' so they compare equal already.


def _line_label(line, max_len=40) -> str:
    """Short rendered label for a build line in a warning message."""
    desc = (line.get('description') or '').strip()
    if len(desc) > max_len:
        desc = desc[:max_len - 1].rstrip() + '…'
    return desc or '(item)'


def check_build(lines) -> List[Warning]:
    """Inspect a build's line items and return a list of Warnings
    for likely-incompatible combinations. Empty list = build looks
    OK to our heuristic detection (which is not authoritative).

    `lines` is the same shape as `build_summary()['lines']` from
    build.py: each line has `id`, `type`, `description`, `qty`,
    `missing` (bool), and other fields. We skip `missing` lines
    (they no longer exist in `parts`) since we can't read their
    descriptions.
    """
    if not lines:
        return []

    # Pre-compute attrs once per line, skip missing items.
    enriched = []
    for ln in lines:
        if ln.get('missing'):
            continue
        attrs = extract_attrs(ln)
        if any(attrs.values()):
            enriched.append((ln, attrs))

    warnings: List[Warning] = []

    # ── Cartridge-family mismatch (mag ↔ barrel/BCG/upper) ────
    # Mag families are stricter than magwell platforms: 5.56 mags
    # won't FEED 6mm ARC reliably even though both are AR-15
    # magwell (Mike + web confirmed 2026-05-27). So we compare on
    # the FAMILY label (FAMILY_OF), not the raw caliber, and use
    # the specific caliber names only when rendering the message
    # text. Two different calibers in the SAME family (e.g. 5.56
    # + .300 BLK on AR-15 mags) produce no warning.
    cal_parts = [(ln, a['caliber']) for ln, a in enriched
                 if a.get('caliber')
                 and ln['type'] in ('barrel', 'bcg', 'mag',
                                    'completeupper', 'strippedupper',
                                    'upperlower')]
    if cal_parts:
        # Group by family — same family = compatible, different =
        # mismatch even if the calibers display differently.
        fam_set = {_family_of(c) for _, c in cal_parts}
        if len(fam_set) > 1:
            # Pick the "primary" by part type: barrel wins, then
            # complete/stripped upper, else first-seen.
            primary = None
            for ln, c in cal_parts:
                if ln['type'] == 'barrel':
                    primary = (ln, c); break
            if primary is None:
                for ln, c in cal_parts:
                    if ln['type'] in ('completeupper', 'strippedupper',
                                      'upperlower'):
                        primary = (ln, c); break
            if primary is None:
                primary = cal_parts[0]
            primary_fam = _family_of(primary[1])
            for ln, c in cal_parts:
                if _family_of(c) == primary_fam:
                    continue
                noun = {
                    'mag': 'Magazine',
                    'barrel': 'Barrel',
                    'bcg': 'BCG',
                    'completeupper': 'Upper assembly',
                    'strippedupper': 'Upper receiver',
                    'upperlower': 'Receiver set',
                }.get(ln['type'], ln['type'])
                msg = (f"{noun} \"{_line_label(ln)}\" looks like {c}, "
                       f"but the rest of the build is {primary[1]}. "
                       f"These cartridges aren't magazine-compatible.")
                warnings.append(Warning(
                    parts=[ln], field='caliber',
                    values=[c, primary[1]], message=msg))

    # ── Magwell-platform mismatch (lower ↔ upper) ─────────────
    # A 9mm-magwell lower (AR-9) cannot accept any AR-15 upper.
    # An AR-10 (.308 magwell) lower can't accept an AR-15 upper.
    # We compare PLATFORMS (ar15 / ar10 / ar9), not raw labels —
    # this lets a Grendel-family upper (6mm ARC, 6.5G, .224 Valk)
    # pair correctly with a 5.56 magwell lower (both AR-15
    # platform) even though the cartridge-family check above
    # would warn about the mag.
    magwells = [(ln, a['magwell']) for ln, a in enriched
                if a.get('magwell')]
    upper_calibers = [(ln, a['caliber']) for ln, a in enriched
                      if a.get('caliber')
                      and ln['type'] in ('barrel', 'completeupper',
                                         'strippedupper')]
    if magwells and upper_calibers:
        for lo_ln, mw in magwells:
            mw_platform = FAMILY_PLATFORM.get(mw, mw)
            for up_ln, uc in upper_calibers:
                up_platform = FAMILY_PLATFORM.get(_family_of(uc), uc)
                if mw_platform != up_platform:
                    lo_noun = {
                        'completelower': 'Complete lower',
                        'strippedlower': 'Stripped lower',
                        'upperlower':    'Receiver set',
                        'lbk':           'Lower build kit',
                        'lpk':           'Lower parts kit',
                    }.get(lo_ln['type'], lo_ln['type'])
                    up_noun = {
                        'barrel':        'barrel',
                        'completeupper': 'complete upper',
                        'strippedupper': 'stripped upper',
                    }.get(up_ln['type'], up_ln['type'])
                    # Human-friendly platform labels for the message.
                    plat_name = {'ar15': 'AR-15', 'ar10': 'AR-10',
                                 'ar9': 'AR-9'}
                    mw_label = plat_name.get(mw_platform, mw)
                    up_label = plat_name.get(up_platform, up_platform)
                    # English "a" vs "an" — both AR-* labels start
                    # with a vowel sound, use "an".
                    article = ('an' if mw_label[:2].lower() == 'ar'
                               else 'a')
                    msg = (f"{lo_noun} \"{_line_label(lo_ln)}\" appears to "
                           f"have {article} {mw_label} "
                           f"magwell, but the {up_noun} "
                           f"\"{_line_label(up_ln)}\" is {uc} "
                           f"({up_label} platform). Different platforms "
                           f"don't interchange.")
                    warnings.append(Warning(
                        parts=[lo_ln, up_ln],
                        field='magwell',
                        values=[mw, uc],
                        message=msg))
                    # One magwell warning per lower — don't spam.
                    break

    return warnings
