from db.channel_sku_mapping import (
    _dedupe_mapping_batch,
    _mapping_match_priority,
    apply_sku_map_to_relation_fields,
    _suggest_for_master,
    reconcile_connection_id_for_channel,
)
from db.channel_sku_prefix_mapping import DEFAULT_SHOPIFY_PREFIX_RULES, _dedupe_longest_first
from db.channel_sku_prefix_mapping import apply_prefix_rules


def test_apply_sku_map_to_relation_fields_parent_and_children():
    sku_map = {"PARENT": "MG-PARENT", "C1": "MG-C1", "C2": "MG-C2"}
    mapped = apply_sku_map_to_relation_fields(
        {
            "product_type": "configurable",
            "variant_list": "C1,C2",
            "configurable_variations": "sku=C1,width=30|sku=C2,width=36",
            "configurable_attributes": "width",
        },
        sku_map,
    )
    assert mapped["variant_list"] == "MG-C1,MG-C2"
    assert "sku=MG-C1,width=30" in mapped["configurable_variations"]
    assert "sku=MG-C2,width=36" in mapped["configurable_variations"]


def test_apply_sku_map_to_relation_fields_child_variant_of():
    mapped = apply_sku_map_to_relation_fields({"variant_of": "PARENT", "product_type": "simple"}, {"PARENT": "MG-PARENT"})
    assert mapped["variant_of"] == "MG-PARENT"


def test_suggest_exact_and_source_item():
    exact = _suggest_for_master({"master_sku": "ABC123", "source_item": "ITEM-1"}, {"ABC123", "OTHER"})
    assert exact["channel_sku"] == "ABC123"
    assert exact["confidence"] == "high"

    by_item = _suggest_for_master({"master_sku": "ABC123", "source_item": "LEGACY-SKU"}, {"LEGACY-SKU"})
    assert by_item["channel_sku"] == "LEGACY-SKU"
    assert by_item["match_source"] == "suggest_source_item"


def test_suggest_prefix_mapped_channel_sku():
    rules = _dedupe_longest_first([(r["master_prefix"], r["channel_prefix"]) for r in DEFAULT_SHOPIFY_PREFIX_RULES])
    effective = apply_prefix_rules("HPW-999", rules, from_master=True)
    assert effective == "HD-CW-999"
    suggestion = _suggest_for_master(
        {"master_sku": "HPW-999", "source_item": ""},
        {"HD-CW-999", "OTHER"},
        effective_channel_sku=effective,
    )
    assert suggestion is not None
    assert suggestion["channel_sku"] == "HD-CW-999"
    assert suggestion["match_source"] == "suggest_prefix_channel_sku"


def test_reconcile_connection_id_for_channel():
    assert reconcile_connection_id_for_channel("magento", native_connection_id=3) == 3
    assert reconcile_connection_id_for_channel("shopify", compat_connection_id=1_000_001) == 1_000_001
    assert reconcile_connection_id_for_channel("plytix", compat_connection_id=2_000_001) == 2_000_001


def test_dedupe_mapping_batch_prefers_exact_over_normalized_channel_sku():
    rows = [
        {
            "master_sku": "FGH-CM3",
            "channel_code": "magento",
            "connection_id": 1,
            "channel_sku": "FGH-CM-3",
            "match_source": "suggest_normalized",
        },
        {
            "master_sku": "FGH-CM-3",
            "channel_code": "magento",
            "connection_id": 1,
            "channel_sku": "FGH-CM-3",
            "match_source": "suggest_exact_sku",
        },
    ]
    deduped = _dedupe_mapping_batch(rows, by_connection=True)
    assert len(deduped) == 1
    assert deduped[0]["master_sku"] == "FGH-CM-3"
    assert deduped[0]["match_source"] == "suggest_exact_sku"


def test_mapping_match_priority_ordering():
    assert _mapping_match_priority("suggest_exact_sku") > _mapping_match_priority("suggest_normalized")
    assert _mapping_match_priority("unknown_source") == 40


def test_filter_weaker_channel_sku_claims_skips_normalized_when_exact_exists():
    from unittest.mock import MagicMock

    from db.channel_sku_mapping import _filter_weaker_channel_sku_claims
    from db.models import ChannelSkuMapping

    existing = ChannelSkuMapping(
        master_sku="FGH-CM-3",
        channel_code="magento",
        connection_id=1,
        channel_sku="FGH-CM-3",
        match_source="suggest_exact_sku",
        mapping_status="active",
    )
    session = MagicMock()
    session.scalars.return_value.all.return_value = [existing]
    incoming = [
        {
            "master_sku": "FGH-CM3",
            "channel_code": "magento",
            "connection_id": 1,
            "channel_sku": "FGH-CM-3",
            "match_source": "suggest_normalized",
        }
    ]
    kept = _filter_weaker_channel_sku_claims(session, incoming, by_connection=True)
    assert kept == []
