from sqlalchemy import select

from db.manual_taxonomy_assignments import replace_manual_taxonomy_assignments
from db.master_taxonomy_product_paths import (
    canonical_taxonomy_leaf_label,
    canonical_master_taxonomy_path_slugs,
    leaf_taxonomy_path_slugs,
    master_taxonomy_nodes_for_product,
)
from db.models import MasterCollectionRegistry, MasterProduct, MasterTaxonomyNode


def _seed_kitchen_taxonomy(session):
    hub = MasterTaxonomyNode(
        parent_id=None,
        node_kind="hub",
        code="kitchen-cabinets",
        name="Kitchen Cabinets",
        path_slug="kitchen-cabinets",
        is_active=True,
    )
    session.add(hub)
    session.flush()
    base = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="category",
        code="base-cabinets",
        name="Kitchen Cabinets / Base Cabinets",
        path_slug="kitchen-cabinets/base-cabinets",
        is_active=True,
    )
    session.add(base)
    session.flush()
    session.add_all(
        [
            MasterTaxonomyNode(
                parent_id=base.id,
                node_kind="category",
                code="single-door",
                name="Kitchen Cabinets / Base Cabinets / Single Door",
                path_slug="kitchen-cabinets/base-cabinets/single-door",
                is_active=True,
            ),
            MasterTaxonomyNode(
                parent_id=hub.id,
                node_kind="collection",
                code="anna-caramel-harvest",
                name="Kitchen Cabinets / Anna Caramel Harvest",
                path_slug="kitchen-cabinets/anna-caramel-harvest",
                is_active=True,
            ),
        ]
    )
    session.flush()
    return hub


def test_canonical_paths_collection_and_product_type(catalog_intent_session):
    session = catalog_intent_session
    _seed_kitchen_taxonomy(session)
    product = MasterProduct(
        sku="ACH-B12",
        name="B12 - Anna Caramel Harvest - Port & Bell - Base",
        category_l1="Kitchen Cabinets",
        collection="Anna Caramel Harvest",
        row_hash="h1",
        is_active=True,
    )
    session.add(product)
    session.flush()

    attrs = {
        "cabinet_type_sub_category_1": "Base Cabinets",
        "cabinet_type_sub_category_2": "Single Door Base Cabinet",
    }
    slugs = canonical_master_taxonomy_path_slugs(session, product, attrs)
    assert slugs[0] == "all-products"
    assert set(slugs) == {
        "all-products",
        "kitchen-cabinets",
        "kitchen-cabinets/anna-caramel-harvest",
        "kitchen-cabinets/base-cabinets",
        "kitchen-cabinets/base-cabinets/single-door",
    }


def test_prefer_short_leaf_over_single_door_wall_cabinet(catalog_intent_session):
    session = catalog_intent_session
    hub = _seed_kitchen_taxonomy(session)
    wall_facet = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="category",
        code="wall-cabinets",
        name="Kitchen Cabinets / Wall Cabinets",
        path_slug="kitchen-cabinets/wall-cabinets",
        is_active=True,
    )
    session.add(wall_facet)
    session.flush()
    session.add_all(
        [
            MasterTaxonomyNode(
                parent_id=wall_facet.id,
                node_kind="category",
                code="single-door",
                name="Kitchen Cabinets / Wall Cabinets / Single Door",
                path_slug="kitchen-cabinets/wall-cabinets/single-door",
                is_active=True,
            ),
            MasterTaxonomyNode(
                parent_id=wall_facet.id,
                node_kind="category",
                code="single-door-wall-cabinet",
                name="Kitchen Cabinets / Wall Cabinets / Single Door Wall Cabinet",
                path_slug="kitchen-cabinets/wall-cabinets/single-door-wall-cabinet",
                is_active=True,
            ),
        ]
    )
    product = MasterProduct(
        sku="ANRO-W0930",
        name="W0930",
        category_l1="Kitchen Cabinets",
        collection="Anna Caramel Harvest",
        row_hash="h2",
        is_active=True,
    )
    session.add(product)
    session.flush()
    slugs = canonical_master_taxonomy_path_slugs(
        session,
        product,
        {
            "cabinet_type_sub_category_1": "Wall Cabinets",
            "cabinet_type_sub_category_2": "Single Door Wall Cabinet",
        },
    )
    assert "kitchen-cabinets/wall-cabinets/single-door" in slugs
    assert "kitchen-cabinets/wall-cabinets/single-door-wall-cabinet" not in slugs
    assert "kitchen-cabinets" in slugs
    assert "all-products" in slugs
    assert "kitchen-cabinets/wall-cabinets" in slugs


def test_infers_exact_wall_leaf_from_product_title_when_l2_missing(catalog_intent_session):
    session = catalog_intent_session
    hub = _seed_kitchen_taxonomy(session)
    wall_facet = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="category",
        code="wall-cabinets",
        name="Kitchen Cabinets / Wall Cabinets",
        path_slug="kitchen-cabinets/wall-cabinets",
        is_active=True,
    )
    session.add(wall_facet)
    session.flush()
    session.add(
        MasterTaxonomyNode(
            parent_id=wall_facet.id,
            node_kind="category",
            code="angle-end-wall-cabinet",
            name="Kitchen Cabinets / Wall Cabinets / Angle End Wall Cabinet",
            path_slug="kitchen-cabinets/wall-cabinets/angle-end-wall-cabinet",
            is_active=True,
        )
    )
    product = MasterProduct(
        sku="ANRO-AEW3018",
        name="AEW3018 - Anna Natural Rift White Oak - Angle End Wall Cabinet",
        category_l1="Kitchen Cabinets",
        collection="Anna Natural Rift White Oak",
        row_hash="h-angle-end",
        is_active=True,
    )
    session.add(product)
    session.flush()

    slugs = canonical_master_taxonomy_path_slugs(
        session,
        product,
        {
            "cabinet_type_sub_category_1": "Wall Cabinets",
        },
    )

    assert "kitchen-cabinets/wall-cabinets/angle-end-wall-cabinet" in slugs
    assert "kitchen-cabinets/wall-cabinets" in slugs


def test_canonical_taxonomy_leaf_label_returns_authoritative_leaf(catalog_intent_session):
    session = catalog_intent_session
    hub = _seed_kitchen_taxonomy(session)
    wall_facet = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="category",
        code="wall-cabinets",
        name="Kitchen Cabinets / Wall Cabinets",
        path_slug="kitchen-cabinets/wall-cabinets",
        is_active=True,
    )
    session.add(wall_facet)
    session.flush()
    session.add(
        MasterTaxonomyNode(
            parent_id=wall_facet.id,
            node_kind="category",
            code="angle-end-wall-cabinet",
            name="Kitchen Cabinets / Wall Cabinets / Angle End Wall Cabinet",
            path_slug="kitchen-cabinets/wall-cabinets/angle-end-wall-cabinet",
            is_active=True,
        )
    )
    product = MasterProduct(
        sku="ANRO-AEW3018",
        name="AEW3018 - Anna Natural Rift White Oak - Angle End Wall Cabinet",
        category_l1="Kitchen Cabinets",
        collection="Anna Natural Rift White Oak",
        row_hash="h-angle-end-leaf",
        is_active=True,
    )
    session.add(product)
    session.flush()

    leaf = canonical_taxonomy_leaf_label(
        session,
        product,
        {"cabinet_type_sub_category_1": "Wall Cabinets"},
    )

    assert leaf == "Angle End Wall Cabinet"


def test_plain_wall_door_subtype_stays_basic_wall(catalog_intent_session):
    session = catalog_intent_session
    hub = _seed_kitchen_taxonomy(session)
    wall_facet = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="category",
        code="wall-cabinets",
        name="Kitchen Cabinets / Wall Cabinets",
        path_slug="kitchen-cabinets/wall-cabinets",
        is_active=True,
    )
    session.add(wall_facet)
    session.flush()
    session.add_all(
        [
            MasterTaxonomyNode(
                parent_id=wall_facet.id,
                node_kind="category",
                code="basic-wall",
                name="Kitchen Cabinets / Wall Cabinets / Basic Wall",
                path_slug="kitchen-cabinets/wall-cabinets/basic-wall",
                is_active=True,
            ),
            MasterTaxonomyNode(
                parent_id=wall_facet.id,
                node_kind="category",
                code="single-door-wall-cabinet",
                name="Kitchen Cabinets / Wall Cabinets / Single Door Wall Cabinet",
                path_slug="kitchen-cabinets/wall-cabinets/single-door-wall-cabinet",
                is_active=True,
            ),
        ]
    )
    product = MasterProduct(
        sku="ACH-W1230",
        name="W1230 - Anna Caramel Harvest - Port & Bell - Wall 30H -- Assembled --",
        category_l1="Kitchen Cabinets",
        collection="Anna Caramel Harvest",
        row_hash="h-basic-wall",
        is_active=True,
    )
    session.add(product)
    session.flush()

    slugs = canonical_master_taxonomy_path_slugs(
        session,
        product,
        {
            "cabinet_type_sub_category_1": "Wall",
            "cabinet_type_sub_category_2": "Single Door Wall Cabinet",
        },
    )
    leaf = canonical_taxonomy_leaf_label(
        session,
        product,
        {
            "cabinet_type_sub_category_1": "Wall",
            "cabinet_type_sub_category_2": "Single Door Wall Cabinet",
        },
    )

    assert "kitchen-cabinets/wall-cabinets/basic-wall" in slugs
    assert "kitchen-cabinets/wall-cabinets/single-door-wall-cabinet" not in slugs
    assert leaf == "Basic Wall"


def test_glass_wall_leaf_is_preserved_when_explicit(catalog_intent_session):
    session = catalog_intent_session
    hub = _seed_kitchen_taxonomy(session)
    wall_facet = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="category",
        code="wall-cabinets",
        name="Kitchen Cabinets / Wall Cabinets",
        path_slug="kitchen-cabinets/wall-cabinets",
        is_active=True,
    )
    session.add(wall_facet)
    session.flush()
    session.add(
        MasterTaxonomyNode(
            parent_id=wall_facet.id,
            node_kind="category",
            code="double-door-glass-wall-cabinet",
            name="Kitchen Cabinets / Wall Cabinets / Double Door Glass Wall Cabinet",
            path_slug="kitchen-cabinets/wall-cabinets/double-door-glass-wall-cabinet",
            is_active=True,
        )
    )
    product = MasterProduct(
        sku="ACH-GDW3030",
        name='30"W x 30"H Double Door Glass Wall Cabinet (GDW3030) - Anna Caramel Harvest | Port & Bell',
        category_l1="Kitchen Cabinets",
        collection="Anna Caramel Harvest",
        row_hash="h-double-door-glass",
        is_active=True,
    )
    session.add(product)
    session.flush()

    slugs = canonical_master_taxonomy_path_slugs(
        session,
        product,
        {
            "cabinet_type_sub_category_1": "Wall",
            "cabinet_type_sub_category_2": "Double Door Glass Wall Cabinet",
        },
    )
    leaf = canonical_taxonomy_leaf_label(
        session,
        product,
        {
            "cabinet_type_sub_category_1": "Wall",
            "cabinet_type_sub_category_2": "Double Door Glass Wall Cabinet",
        },
    )

    assert "kitchen-cabinets/wall-cabinets/double-door-glass-wall-cabinet" in slugs
    assert leaf == "Double Door Glass Wall Cabinet"


def test_bathroom_vanity_stays_under_bathroom_hub(catalog_intent_session):
    session = catalog_intent_session
    hub = MasterTaxonomyNode(
        parent_id=None,
        node_kind="hub",
        code="bathroom-vanities",
        name="Bathroom Vanities",
        path_slug="bathroom-vanities",
        is_active=True,
    )
    session.add(hub)
    session.flush()
    base = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="category",
        code="base-cabinets",
        name="Bathroom Vanities / Base Cabinets",
        path_slug="bathroom-vanities/base-cabinets",
        is_active=True,
    )
    session.add(base)
    session.flush()
    kitchen = MasterTaxonomyNode(
        parent_id=None,
        node_kind="hub",
        code="kitchen-cabinets",
        name="Kitchen Cabinets",
        path_slug="kitchen-cabinets",
        is_active=True,
    )
    session.add(kitchen)
    session.flush()
    kitchen_base = MasterTaxonomyNode(
        parent_id=kitchen.id,
        node_kind="category",
        code="base-cabinets-k",
        name="Kitchen Cabinets / Base Cabinets",
        path_slug="kitchen-cabinets/base-cabinets",
        is_active=True,
    )
    session.add(kitchen_base)
    session.flush()
    session.add_all(
        [
            MasterTaxonomyNode(
                parent_id=base.id,
                node_kind="category",
                code="special-base",
                name="Bathroom Vanities / Base Cabinets / Special Base",
                path_slug="bathroom-vanities/base-cabinets/special-base",
                is_active=True,
            ),
            MasterTaxonomyNode(
                parent_id=hub.id,
                node_kind="collection",
                code="bedford",
                name="Bathroom Vanities / Bedford",
                path_slug="bathroom-vanities/bedford",
                is_active=True,
            ),
            MasterTaxonomyNode(
                parent_id=kitchen_base.id,
                node_kind="category",
                code="special-base-k",
                name="Kitchen Cabinets / Base Cabinets / Special Base",
                path_slug="kitchen-cabinets/base-cabinets/special-base",
                is_active=True,
            ),
        ]
    )
    product = MasterProduct(
        sku="PBV-BED-24WH",
        name="Bedford 24",
        category_l1="Bathroom Vanities",
        collection="Bedford",
        row_hash="h3",
        is_active=True,
    )
    session.add(product)
    session.flush()
    slugs = canonical_master_taxonomy_path_slugs(
        session,
        product,
        {
            "cabinet_type_sub_category_1": "Base Cabinets",
            "cabinet_type_sub_category_2": "Special Base",
        },
    )
    assert "all-products" in slugs
    assert "bathroom-vanities" not in slugs
    assert "bathroom-vanities/bedford" in slugs
    assert "bathroom-vanities/base-cabinets/special-base" in slugs
    assert "bathroom-vanities/base-cabinets" in slugs
    assert not any(slug.startswith("kitchen-cabinets") for slug in slugs)


def test_leaf_taxonomy_path_slugs_drops_hub():
    assert leaf_taxonomy_path_slugs(
        ["kitchen-cabinets", "kitchen-cabinets/anna-caramel-harvest"]
    ) == ["kitchen-cabinets/anna-caramel-harvest"]


def test_expand_shopping_facet_ancestors_keeps_l1_for_master_listing():
    from db.master_taxonomy_product_paths import expand_shopping_facet_ancestor_paths

    assert expand_shopping_facet_ancestor_paths(
        [
            "kitchen-cabinets/anna-caramel-harvest",
            "kitchen-cabinets/wall-cabinets/corner-wall",
        ]
    ) == [
        "kitchen-cabinets/anna-caramel-harvest",
        "kitchen-cabinets/wall-cabinets/corner-wall",
        "kitchen-cabinets/wall-cabinets",
    ]
    assert expand_shopping_facet_ancestor_paths(
        [
            "kitchen-cabinets/anna-caramel-harvest",
            "kitchen-cabinets/wall-cabinets/corner-wall",
        ],
        include_hub=True,
    ) == [
        "kitchen-cabinets/anna-caramel-harvest",
        "kitchen-cabinets",
        "kitchen-cabinets/wall-cabinets/corner-wall",
        "kitchen-cabinets/wall-cabinets",
    ]


def test_expand_keeps_l3_leaf_when_taxonomy_node_missing(catalog_intent_session):
    """BF fillers must not demote to L2-only when fillers node is temporarily absent."""
    from db.master_taxonomy_intent import _NodeIndex
    from db.master_taxonomy_product_paths import expand_shopping_facet_ancestor_paths
    from db.models import MasterTaxonomyNode

    session = catalog_intent_session
    hub = MasterTaxonomyNode(
        parent_id=None,
        node_kind="hub",
        code="kitchen-cabinets",
        name="Kitchen Cabinets",
        path_slug="kitchen-cabinets",
        is_active=True,
    )
    session.add(hub)
    session.flush()
    session.add(
        MasterTaxonomyNode(
            parent_id=hub.id,
            node_kind="category",
            code="panels-and-fillers",
            name="Kitchen Cabinets / Panels And Fillers",
            path_slug="kitchen-cabinets/panels-and-fillers",
            is_active=True,
        )
    )
    session.flush()
    index = _NodeIndex.load(session)

    expanded = expand_shopping_facet_ancestor_paths(
        ["kitchen-cabinets/panels-and-fillers/fillers"],
        index=index,
        include_hub=True,
    )
    assert "kitchen-cabinets/panels-and-fillers/fillers" in expanded
    assert "kitchen-cabinets/panels-and-fillers" in expanded
    assert "kitchen-cabinets" in expanded


def test_is_magento_outbound_category_membership_filters_hub_and_facet():
    from db.master_taxonomy_product_paths import is_magento_outbound_category_membership

    assert is_magento_outbound_category_membership("all-products") is True
    assert is_magento_outbound_category_membership(
        "kitchen-cabinets/anna-caramel-harvest",
        taxonomy_kind="collection",
    ) is True
    assert is_magento_outbound_category_membership("kitchen-cabinets") is False
    assert is_magento_outbound_category_membership("kitchen-cabinets/wall-cabinets") is False
    assert is_magento_outbound_category_membership(
        "kitchen-cabinets/wall-cabinets/single-door-glass-wall-cabinet"
    ) is True
    assert is_magento_outbound_category_membership(
        "kitchen-cabinets/base-cabinets/single-door"
    ) is True
    assert is_magento_outbound_category_membership("samples") is True
    assert is_magento_outbound_category_membership("sample") is True
    assert is_magento_outbound_category_membership("product-category/sample_doors") is True


def test_master_taxonomy_nodes_expected_vs_stale(catalog_intent_session):
    from db.channel_listing_path import bulk_assign_listing_paths, upsert_listing_path

    session = catalog_intent_session
    _seed_kitchen_taxonomy(session)
    product = MasterProduct(
        sku="ACH-B12",
        name="B12",
        category_l1="Kitchen Cabinets",
        collection="Anna Caramel Harvest",
        row_hash="h1",
        is_active=True,
    )
    session.add(product)
    session.flush()
    upsert_listing_path(session, path_slug="kitchen-cabinets", title="Kitchen Cabinets", path_kind="hub")
    upsert_listing_path(
        session,
        path_slug="kitchen-cabinets/anna-caramel-harvest",
        title="Anna Caramel Harvest",
        path_kind="collection",
    )
    bulk_assign_listing_paths(
        session,
        path_slugs=["kitchen-cabinets", "kitchen-cabinets/anna-caramel-harvest"],
        skus=["ACH-B12"],
        dry_run=False,
    )
    session.flush()

    attrs = {
        "cabinet_type_sub_category_1": "Base Cabinets",
        "cabinet_type_sub_category_2": "Single Door Base Cabinet",
    }
    nodes = master_taxonomy_nodes_for_product(session, product, attrs=attrs)
    by_slug = {row["path_slug"]: row["source"] for row in nodes}
    # Collection is assigned; hub is an ancestor of that leaf so it must not
    # appear as a false "(expected)" Needs-reconciliation chip.
    assert by_slug["kitchen-cabinets/anna-caramel-harvest"] == "assigned"
    assert "kitchen-cabinets" not in by_slug
    assert "kitchen-cabinets/base-cabinets" not in by_slug
    # Missing L3 leaf still surfaces as expected.
    assert by_slug["kitchen-cabinets/base-cabinets/single-door"] == "expected"


def test_master_taxonomy_nodes_assigned_l3_covers_hub_and_facet(catalog_intent_session):
    """Assigned Stacked Wall must not leave Kitchen Cabinets / Wall Cabinets as (expected)."""
    from db.channel_listing_path import bulk_assign_listing_paths, upsert_listing_path

    session = catalog_intent_session
    hub = _seed_kitchen_taxonomy(session)
    wall = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="category",
        code="wall-cabinets",
        name="Kitchen Cabinets / Wall Cabinets",
        path_slug="kitchen-cabinets/wall-cabinets",
        is_active=True,
    )
    session.add(wall)
    session.flush()
    stacked = MasterTaxonomyNode(
        parent_id=wall.id,
        node_kind="category",
        code="stacked-wall",
        name="Kitchen Cabinets / Wall Cabinets / Stacked Wall",
        path_slug="kitchen-cabinets/wall-cabinets/stacked-wall",
        is_active=True,
    )
    session.add(stacked)
    product = MasterProduct(
        sku="ACH-GDW1215",
        name='12"W x 15"H Single Door Glass Wall Cabinet (GDW1215)',
        category_l1="Kitchen Cabinets",
        collection="Anna Caramel Harvest",
        row_hash="h-gdw-stacked",
        is_active=True,
    )
    session.add(product)
    session.flush()
    for slug, title, kind in (
        ("kitchen-cabinets", "Kitchen Cabinets", "hub"),
        ("kitchen-cabinets/wall-cabinets", "Wall Cabinets", "category"),
        ("kitchen-cabinets/wall-cabinets/stacked-wall", "Stacked Wall", "category"),
        ("kitchen-cabinets/anna-caramel-harvest", "Anna Caramel Harvest", "collection"),
    ):
        upsert_listing_path(session, path_slug=slug, title=title, path_kind=kind)
    bulk_assign_listing_paths(
        session,
        path_slugs=[
            "kitchen-cabinets",
            "kitchen-cabinets/wall-cabinets",
            "kitchen-cabinets/wall-cabinets/stacked-wall",
            "kitchen-cabinets/anna-caramel-harvest",
        ],
        skus=["ACH-GDW1215"],
        dry_run=False,
    )
    session.flush()

    nodes = master_taxonomy_nodes_for_product(
        session,
        product,
        attrs={"cabinet_type_sub_category_1": "Wall"},
    )
    by_slug = {row["path_slug"]: row["source"] for row in nodes}
    assert by_slug["kitchen-cabinets/wall-cabinets/stacked-wall"] == "assigned"
    assert by_slug["kitchen-cabinets/anna-caramel-harvest"] == "assigned"
    assert "kitchen-cabinets" not in by_slug
    assert "kitchen-cabinets/wall-cabinets" not in by_slug
    assert all(row["source"] != "expected" for row in nodes)


def test_manual_taxonomy_override_drives_canonical_paths_and_leaf(catalog_intent_session):
    session = catalog_intent_session
    hub = _seed_kitchen_taxonomy(session)
    maya = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="collection",
        code="maya-black-rift-white-oak",
        name="Kitchen Cabinets / Maya Black Rift White Oak",
        path_slug="kitchen-cabinets/maya-black-rift-white-oak",
        is_active=True,
    )
    fillers = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="category",
        code="panels-and-fillers",
        name="Kitchen Cabinets / Panels And Fillers",
        path_slug="kitchen-cabinets/panels-and-fillers",
        is_active=True,
    )
    session.add_all([maya, fillers])
    session.flush()
    session.add(
        MasterTaxonomyNode(
            parent_id=fillers.id,
            node_kind="category",
            code="fillers",
            name="Kitchen Cabinets / Panels And Fillers / Fillers",
            path_slug="kitchen-cabinets/panels-and-fillers/fillers",
            is_active=True,
        )
    )
    session.add(
        MasterCollectionRegistry(
            code="MAYA",
            name="Maya Black Rift White Oak",
            path_slug="kitchen-cabinets/maya-black-rift-white-oak",
            is_active=True,
            aliases={"source_collection_code": "MAYA", "alias_codes": ["MAYA"]},
        )
    )
    product = MasterProduct(
        sku="PB-BRO-BF3",
        name="BF3 - Black Rift White Oak - Port & Bell - Filler Base",
        category_l1="Kitchen Cabinets",
        collection="Merrill Slate",
        row_hash="h-manual-override-paths",
        is_active=True,
    )
    session.add(product)
    session.flush()

    replace_manual_taxonomy_assignments(
        session,
        {
            "templates": [
                {
                    "source_sku": "BF3",
                    "canonical_taxonomy_path_slug": "kitchen-cabinets/panels-and-fillers/fillers",
                    "canonical_taxonomy_path_label": "Kitchen Cabinets / Panels And Fillers / Fillers",
                    "shopping_l1": "panels-and-fillers",
                    "shopping_l2": "panels-and-fillers/fillers",
                    "l2_category": "Panels And Fillers",
                    "l3_category": "Fillers",
                    "collections": [
                        {
                            "collection_code": "MAYA",
                            "source_collection_code": "MAYA",
                            "sku_prefix": "MAYA",
                            "collection_name": "Maya Black Rift White Oak",
                            "master_sku": "PB-BRO-BF3",
                        }
                    ],
                }
            ]
        },
    )

    slugs = canonical_master_taxonomy_path_slugs(session, product, attrs={})
    leaf = canonical_taxonomy_leaf_label(session, product, attrs={})

    assert slugs == [
        "all-products",
        "kitchen-cabinets/maya-black-rift-white-oak",
        "kitchen-cabinets",
        "kitchen-cabinets/panels-and-fillers",
        "kitchen-cabinets/panels-and-fillers/fillers",
    ]
    assert leaf == "Fillers"


def test_manual_taxonomy_override_drives_expected_nodes_before_guessing(catalog_intent_session):
    from db.channel_listing_path import bulk_assign_listing_paths, upsert_listing_path

    session = catalog_intent_session
    hub = _seed_kitchen_taxonomy(session)
    maya = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="collection",
        code="maya-black-rift-white-oak",
        name="Kitchen Cabinets / Maya Black Rift White Oak",
        path_slug="kitchen-cabinets/maya-black-rift-white-oak",
        is_active=True,
    )
    fillers = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="category",
        code="panels-and-fillers",
        name="Kitchen Cabinets / Panels And Fillers",
        path_slug="kitchen-cabinets/panels-and-fillers",
        is_active=True,
    )
    session.add_all([maya, fillers])
    session.flush()
    session.add(
        MasterTaxonomyNode(
            parent_id=fillers.id,
            node_kind="category",
            code="fillers",
            name="Kitchen Cabinets / Panels And Fillers / Fillers",
            path_slug="kitchen-cabinets/panels-and-fillers/fillers",
            is_active=True,
        )
    )
    session.add(
        MasterCollectionRegistry(
            code="MAYA",
            name="Maya Black Rift White Oak",
            path_slug="kitchen-cabinets/maya-black-rift-white-oak",
            is_active=True,
            aliases={"source_collection_code": "MAYA", "alias_codes": ["MAYA"]},
        )
    )
    product = MasterProduct(
        sku="PB-BRO-BF3",
        name="BF3 - Black Rift White Oak - Port & Bell - Filler Base",
        category_l1="Kitchen Cabinets",
        collection="Merrill Slate",
        row_hash="h-manual-override-nodes",
        is_active=True,
    )
    session.add(product)
    session.flush()

    replace_manual_taxonomy_assignments(
        session,
        {
            "templates": [
                {
                    "source_sku": "BF3",
                    "canonical_taxonomy_path_slug": "kitchen-cabinets/panels-and-fillers/fillers",
                    "canonical_taxonomy_path_label": "Kitchen Cabinets / Panels And Fillers / Fillers",
                    "shopping_l1": "panels-and-fillers",
                    "shopping_l2": "panels-and-fillers/fillers",
                    "l2_category": "Panels And Fillers",
                    "l3_category": "Fillers",
                    "collections": [
                        {
                            "collection_code": "MAYA",
                            "source_collection_code": "MAYA",
                            "sku_prefix": "MAYA",
                            "collection_name": "Maya Black Rift White Oak",
                            "master_sku": "PB-BRO-BF3",
                        }
                    ],
                }
            ]
        },
    )

    for slug, title, kind in (
        ("kitchen-cabinets/maya-black-rift-white-oak", "Maya Black Rift White Oak", "collection"),
        ("kitchen-cabinets/panels-and-fillers", "Panels And Fillers", "category"),
        ("kitchen-cabinets/panels-and-fillers/fillers", "Fillers", "category"),
    ):
        upsert_listing_path(session, path_slug=slug, title=title, path_kind=kind)
    bulk_assign_listing_paths(
        session,
        path_slugs=["kitchen-cabinets/maya-black-rift-white-oak"],
        skus=["PB-BRO-BF3"],
        dry_run=False,
    )
    session.flush()

    nodes = master_taxonomy_nodes_for_product(session, product, attrs={})
    by_slug = {row["path_slug"]: row["source"] for row in nodes}

    assert by_slug["kitchen-cabinets/maya-black-rift-white-oak"] == "assigned"
    assert by_slug["kitchen-cabinets/panels-and-fillers/fillers"] == "expected"
    assert "kitchen-cabinets/anna-caramel-harvest" not in by_slug


def test_source_sku_manual_taxonomy_override_is_authoritative_for_paths(catalog_intent_session):
    session = catalog_intent_session
    hub = _seed_kitchen_taxonomy(session)
    wall = MasterTaxonomyNode(
        parent_id=hub.id,
        node_kind="category",
        code="wall-cabinets",
        name="Kitchen Cabinets / Wall Cabinets",
        path_slug="kitchen-cabinets/wall-cabinets",
        is_active=True,
    )
    session.add(wall)
    session.flush()
    session.add(
        MasterTaxonomyNode(
            parent_id=wall.id,
            node_kind="category",
            code="basic-wall",
            name="Kitchen Cabinets / Wall Cabinets / Basic Wall",
            path_slug="kitchen-cabinets/wall-cabinets/basic-wall",
            is_active=True,
        )
    )
    session.add(
        MasterTaxonomyNode(
            parent_id=hub.id,
            node_kind="collection",
            code="maya-black-rift-white-oak",
            name="Kitchen Cabinets / Maya Black Rift White Oak",
            path_slug="kitchen-cabinets/maya-black-rift-white-oak",
            is_active=True,
        )
    )
    session.flush()

    product = MasterProduct(
        sku="ACH-W0930",
        source_item="W0930",
        name="W0930 - Anna Caramel Harvest - Wall Cabinet",
        category_l1="Kitchen Cabinets",
        collection="Wrong Collection",
        row_hash="h-source-sku-manual-authoritative",
        is_active=True,
    )
    session.add(product)
    session.flush()

    replace_manual_taxonomy_assignments(
        session,
        {
            "templates": [
                {
                    "source_sku": "W0930",
                    "canonical_taxonomy_path_slug": "kitchen-cabinets/wall-cabinets/basic-wall",
                    "canonical_taxonomy_path_label": "Kitchen Cabinets / Wall Cabinets / Basic Wall",
                    "shopping_l1": "wall-cabinets",
                    "shopping_l2": "wall-cabinets/basic-wall",
                    "l2_category": "Wall Cabinets",
                    "l3_category": "Basic Wall",
                    "collections": [
                        {
                            "collection_code": "MAYA",
                            "source_collection_code": "MAYA",
                            "sku_prefix": "MAYA",
                            "collection_name": "Maya Black Rift White Oak",
                            "master_sku": "MAYA-W0930",
                        }
                    ],
                }
            ]
        },
    )

    slugs = canonical_master_taxonomy_path_slugs(
        session,
        product,
        {
            "cabinet_type_sub_category_1": "Accessories",
            "cabinet_type_sub_category_2": "Wrong Type",
        },
    )

    assert slugs == [
        "all-products",
        "kitchen-cabinets",
        "kitchen-cabinets/wall-cabinets",
        "kitchen-cabinets/wall-cabinets/basic-wall",
    ]
    assert "kitchen-cabinets/maya-black-rift-white-oak" not in slugs
