"""Tests for height-from-SKU derivation in normalize (Plytix cabinet SKU patterns)."""
import pandas as pd
import pytest

from normalize import (
    _try_derive_height_from_sku,
    _get_child_value,
    _relation_sku,
)
from magento.catalog_normalize import normalize_master_catalog_df
from settings import load_magento_config


def test_try_derive_height_from_sku():
    """SKU suffix patterns: W1542->42, W1536->36, W1530->30."""
    assert _try_derive_height_from_sku("RTA-ASW-W1542") == "42"
    assert _try_derive_height_from_sku("RTA-ASW-W1536") == "36"
    assert _try_derive_height_from_sku("RTA-ASW-W1530") == "30"
    assert _try_derive_height_from_sku("SOME-W1530") == "30"
    assert _try_derive_height_from_sku("W1542") == "42"
    # Plausible range 6-96
    assert _try_derive_height_from_sku("X12") == "12"
    assert _try_derive_height_from_sku("X96") == "96"
    assert _try_derive_height_from_sku("X05") is None  # 05 < 6
    assert _try_derive_height_from_sku("X99") is None  # 99 > 96
    assert _try_derive_height_from_sku("NO-DIGITS") is None
    assert _try_derive_height_from_sku("") is None


def test_get_child_value_fallback_height_from_sku():
    """When height column missing/wrong, derive from child SKU."""
    df = pd.DataFrame([
        {"sku": "RTA-ASW-W1542", "name": "Cab 42H", "price": "100"},  # no height col
        {"sku": "RTA-ASW-W1536", "name": "Cab 36H", "price": "90"},
        {"sku": "RTA-ASW-W1530", "name": "Cab 30H", "price": "80"},
    ])
    assert _get_child_value(df, "RTA-ASW-W1542", "height") == "42"
    assert _get_child_value(df, "RTA-ASW-W1536", "height") == "36"
    assert _get_child_value(df, "RTA-ASW-W1530", "height") == "30"
    # width still needs column - no SKU fallback for width
    assert _get_child_value(df, "RTA-ASW-W1542", "width") is None


def test_normalize_parent_configurable_height_from_sku():
    """Parent RTA-ASW-W15 with children W1542,W1536,W1530 gets height from SKU when columns missing."""
    cfg = load_magento_config()
    df = pd.DataFrame([
        {
            "sku": "RTA-ASW-W15",
            "name": "Anna Snow White",
            "product_type": "configurable",
            "price": "0",
            "variant_list": "RTA-ASW-W1542,RTA-ASW-W1536,RTA-ASW-W1530",
            "configurable_variation_axis": "height",
            "configurable_variation_labels": "height=Height (inches)",
        },
        {
            "sku": "RTA-ASW-W1542",
            "name": "Cab 42H",
            "product_type": "simple",
            "price": "215.25",
            "variant_of": "",
            # no height/height_in - will use SKU fallback
        },
        {
            "sku": "RTA-ASW-W1536",
            "name": "Cab 36H",
            "product_type": "simple",
            "price": "189",
            "variant_of": "",
        },
        {
            "sku": "RTA-ASW-W1530",
            "name": "Cab 30H",
            "product_type": "simple",
            "price": "157.5",
            "variant_of": "",
        },
    ])
    out, quarantine = normalize_master_catalog_df(df, cfg, enforce_required_name=False)
    assert "RTA-ASW-W15" in out["sku"].values, "Parent must not be quarantined"
    parent = out[out["sku"] == "RTA-ASW-W15"].iloc[0]
    assert "height" in str(parent.get("configurable_attributes", ""))
    cv = str(parent.get("configurable_variations", ""))
    assert "RTA-ASW-W1542" in cv and "42" in cv
    assert "RTA-ASW-W1536" in cv and "36" in cv
    assert "RTA-ASW-W1530" in cv and "30" in cv
    assert quarantine.empty or "RTA-ASW-W15" not in quarantine["sku"].values


def test_normalize_preserves_master_catalog_relation_fields():
    cfg = load_magento_config()
    df = pd.DataFrame([
        {
            "sku": "ACH-B-PARENT",
            "name": "Anna Cabinet Parent",
            "product_type": "configurable",
            "price": "0",
            "variant_list": "ACH-B12,ACH-B15",
            "configurable_attributes": "width",
            "configurable_variations": "sku=ACH-B12,width=12|sku=ACH-B15,width=15",
        },
        {"sku": "ACH-B12", "name": "Cab 12", "product_type": "simple", "price": "10", "variation_width_in": "12"},
        {"sku": "ACH-B15", "name": "Cab 15", "product_type": "simple", "price": "11", "variation_width_in": "15"},
    ])
    out, quarantine = normalize_master_catalog_df(df, cfg, enforce_required_name=False, enforce_required_price=False)
    assert quarantine.empty
    parent = out[out["sku"] == "ACH-B-PARENT"].iloc[0]
    assert parent["configurable_variations"] == "sku=ACH-B12,width=12|sku=ACH-B15,width=15"
    assert parent["configurable_attributes"] == "width"


def test_get_child_value_reads_variation_width_in_for_width_axis():
    df = pd.DataFrame([
        {"sku": "ACH-B12", "variation_width_in": "12"},
        {"sku": "ACH-B15", "variation_width_in": "15"},
    ])
    assert _get_child_value(df, "ACH-B12", "width") == "12"


def test_normalize_master_catalog_row_without_price_when_price_not_required():
    cfg = load_magento_config()
    df = pd.DataFrame([{"sku": "ACH-B12", "name": "Cabinet", "product_type": "simple"}])
    out, quarantine = normalize_master_catalog_df(
        df,
        cfg,
        enforce_required_name=False,
        enforce_required_price=False,
    )
    assert len(out) == 1
    assert quarantine.empty


def test_relation_sku_treats_nan_as_empty():
    assert _relation_sku(float("nan")) == ""
    assert _relation_sku("nan") == ""
    assert _relation_sku("PARENT-1") == "PARENT-1"


def test_normalize_master_catalog_clears_nan_variant_of():
    cfg = load_magento_config()
    df = pd.DataFrame(
        [
            {
                "sku": "CHILD-1",
                "name": "Child",
                "price": "10",
                "product_type": "simple",
                "variant_of": float("nan"),
            },
            {
                "sku": "PARENT-1",
                "name": "Parent",
                "price": "0",
                "product_type": "configurable",
                "variant_list": "CHILD-1",
                "configurable_variations": "sku=CHILD-1,width=12",
                "configurable_attributes": "width",
            },
        ]
    )
    out, quarantine = normalize_master_catalog_df(
        df,
        cfg,
        enforce_required_name=False,
        enforce_required_price=False,
    )
    child = out[out["sku"] == "CHILD-1"].iloc[0]
    assert child["variant_of"] == ""
    assert quarantine.empty
