from db.master_taxonomy_registry import (
    MATCH_MATCHED,
    MATCH_PROPOSED,
    registry_code_from_name,
    resolve_or_propose_registry_entities,
    summarize_import_registry_intent,
)


def test_registry_code_from_name_slugifies():
    assert registry_code_from_name("Anna Stone Gray") == "anna-stone-gray"


def test_resolve_proposes_unknown_brand():
    class Session:
        def scalar(self, stmt):
            return None

        def scalars(self, stmt):
            return self

        def all(self):
            return []

    resolution = resolve_or_propose_registry_entities(
        Session(),
        {"brand": "Port & Bell", "product_family": "Kitchen Cabinets", "collection": "Anna Stone Gray"},
    )
    assert resolution["brand"]["status"] == MATCH_PROPOSED
    assert resolution["brand"]["proposed"]["code"] == registry_code_from_name("Port & Bell")
    assert resolution["collection"]["status"] == MATCH_PROPOSED


def test_summarize_import_registry_intent_dedupes_proposals():
    class Session:
        def scalar(self, stmt):
            return None

        def scalars(self, stmt):
            return self

        def all(self):
            return []

    records = [
        {"brand": "Port & Bell", "product_family": "Kitchen Cabinets", "collection": "Anna Stone Gray"},
        {"brand": "Port & Bell", "product_family": "Kitchen Cabinets", "collection": "Belmont"},
    ]
    summary = summarize_import_registry_intent(Session(), records)
    assert summary["row_count"] == 2
    assert len(summary["proposed_brands"]) == 1
    assert len(summary["proposed_collections"]) == 2


def test_summarize_counts_matched_entities():
    class Brand:
        id = 1
        code = "port-bell"
        name = "Port & Bell"
        aliases = None
        is_active = True
        notes = None

    class Session:
        def scalar(self, stmt):
            return Brand()

        def scalars(self, stmt):
            return self

        def all(self):
            return [Brand()]

    summary = summarize_import_registry_intent(
        Session(),
        [{"brand": "Port & Bell", "product_family": "Kitchen Cabinets", "collection": "Anna Stone Gray"}],
    )
    assert summary["matched_counts"]["brand"] == 1
    assert summary["proposed_brands"] == []


def test_upsert_preserves_aliases_when_omitted():
    class Row:
        id = 1
        code = "port-bell"
        name = "Port & Bell"
        aliases = {"items": ["P&B"]}
        is_active = True
        notes = None

    class Session:
        def get(self, model, entity_id):
            return Row() if entity_id == 1 else None

        def scalar(self, stmt):
            return Row()

        def flush(self):
            return None

    from db.master_taxonomy_registry import _upsert_entity
    from db.models import MasterBrand

    result = _upsert_entity(Session(), MasterBrand, {"id": 1, "name": "Port & Bell", "code": "port-bell"})
    assert result["aliases"] == ["P&B"]
