"""Unit tests for ngsite.compatibility — the (non-authoritative) build
compatibility heuristics: caliber extraction + cross-part mismatch
warnings. The contract these pin: detect a real mismatch, stay silent on
compatible/insufficient data, and never raise on messy input.
"""
from ngsite import compatibility as compat


def test_extract_attrs_normalizes_556():
    attrs = compat.extract_attrs(
        {"type": "barrel", "description": '16" 5.56 NATO barrel'})
    assert attrs.get("caliber") == "5.56"


def test_extract_attrs_normalizes_308():
    attrs = compat.extract_attrs(
        {"type": "barrel", "description": ".308 Win match barrel"})
    assert attrs.get("caliber") == ".308"


def test_extract_attrs_tolerates_missing_fields():
    assert compat.extract_attrs({}) == {}
    assert compat.extract_attrs({"type": "barrel"}) == {"caliber": None}


def test_extract_attrs_only_returns_keys_for_that_type():
    # A trigger carries no caliber/magwell attrs.
    assert compat.extract_attrs(
        {"type": "trigger", "description": "5.56 marketing fluff"}) == {}


def test_check_build_flags_caliber_family_mismatch():
    warnings = compat.check_build([
        {"id": 1, "type": "barrel", "description": "16in 5.56 NATO barrel",
         "qty": 1, "missing": False},
        {"id": 2, "type": "mag", "description": ".308 Win 20rd magazine",
         "qty": 1, "missing": False},
    ])
    assert warnings, "expected a mismatch warning for 5.56 barrel + .308 mag"
    assert any(w.field == "caliber" for w in warnings)


def test_check_build_silent_on_compatible_calibers():
    warnings = compat.check_build([
        {"id": 1, "type": "barrel", "description": "5.56 barrel",
         "qty": 1, "missing": False},
        {"id": 2, "type": "bcg", "description": "5.56/.223 BCG",
         "qty": 1, "missing": False},
    ])
    assert warnings == []


def test_check_build_empty_and_missing_lines():
    assert compat.check_build([]) == []
    # A `missing` line (no longer in parts) is skipped, not crashed on.
    assert compat.check_build(
        [{"id": 9, "type": "barrel", "missing": True}]) == []
