"""Canonical attribute types, admin UI controls, and channel representations.

Canonical type is the stored business shape. UI control is how an admin edits it.
Channel representation is how Magento/Shopify receive it. These are independent.
"""

from __future__ import annotations

from typing import Any


CANONICAL_DATA_TYPES = (
    "text",
    "textarea",
    "integer",
    "decimal",
    "boolean",
    "select",
    "multiselect",
    "date",
    "datetime",
    "html",
    "image",
)

ADMIN_UI_CONTROLS = (
    "text_field",
    "textarea",
    "dropdown",
    "radio",
    "checkbox",
    "checkbox_group",
    "multi_select",
    "number_input",
    "date_picker",
)

REVIEW_STATUSES = (
    "pending_review",
    "approved",
    "modified",
    "merged",
    "excluded",
    "conflict",
)

VALUE_REVIEW_STATUSES = (
    "pending_review",
    "approved",
    "modified",
    "merged",
    "excluded",
)

LIFECYCLE_STATUSES = ("active", "inactive", "deprecated")

OWNER_SCOPES = ("product", "category")
DEFAULT_OWNER_SCOPE = "product"

APPLY_READY_STATUSES = frozenset({"approved", "modified"})
SELECTABLE_TYPES = frozenset({"select", "multiselect"})

DEFAULT_UI_CONTROL = {
    "text": "text_field",
    "textarea": "textarea",
    "integer": "number_input",
    "decimal": "number_input",
    "boolean": "checkbox",
    "select": "dropdown",
    "multiselect": "multi_select",
    "date": "date_picker",
    "datetime": "date_picker",
    "html": "textarea",
    "image": "text_field",
}

DATA_TYPE_ALIASES = {
    "varchar": "text",
    "string": "text",
    "input field": "text",
    "single_line_text_field": "text",
    "text": "text",
    "textarea": "textarea",
    "multi_line_text_field": "textarea",
    "html": "html",
    "int": "integer",
    "integer": "integer",
    "decimal": "decimal",
    "float": "decimal",
    "number": "decimal",
    "price": "decimal",
    "weight": "decimal",
    "bool": "boolean",
    "boolean": "boolean",
    "yesno": "boolean",
    "image": "image",
    "media": "image",
    "media_image": "image",
    "select": "select",
    "dropdown": "select",
    "enum": "select",
    "option": "select",
    "multiselect": "multiselect",
    "multi_select": "multiselect",
    "enum[]": "multiselect",
    "date": "date",
    "datetime": "datetime",
}

MAGENTO_FRONTEND_FOR_TYPE = {
    "text": "text",
    "textarea": "textarea",
    "integer": "text",
    "decimal": "price",
    "boolean": "boolean",
    "select": "select",
    "multiselect": "multiselect",
    "date": "date",
    "datetime": "datetime",
    "html": "textarea",
    "image": "media_image",
}

SHOPIFY_KIND_FOR_TYPE = {
    "text": "metafield",
    "textarea": "metafield",
    "integer": "metafield",
    "decimal": "metafield",
    "boolean": "metafield",
    "select": "metafield",
    "multiselect": "metafield",
    "date": "metafield",
    "datetime": "metafield",
    "html": "metafield",
    "image": "metafield",
}

SHOPIFY_METAFIELD_TYPE = {
    "text": "single_line_text_field",
    "textarea": "multi_line_text_field",
    "integer": "number_integer",
    "decimal": "number_decimal",
    "boolean": "boolean",
    "select": "single_line_text_field",
    "multiselect": "list.single_line_text_field",
    "date": "date",
    "datetime": "date_time",
    "html": "multi_line_text_field",
    "image": "url",
}

UI_CONTROL_LABELS = {
    "text_field": "Text field",
    "textarea": "Textarea",
    "dropdown": "Dropdown",
    "radio": "Radio",
    "checkbox": "Checkbox",
    "checkbox_group": "Checkbox group",
    "multi_select": "Multi-select",
    "number_input": "Number input",
    "date_picker": "Date picker",
}


def map_canonical_data_type(raw: object) -> str:
    text = str(raw or "text").strip().lower()
    return DATA_TYPE_ALIASES.get(text, "text")


def default_ui_control(data_type: str) -> str:
    return DEFAULT_UI_CONTROL.get(str(data_type or "text"), "text_field")


def magento_frontend_input(data_type: str) -> str:
    return MAGENTO_FRONTEND_FOR_TYPE.get(str(data_type or "text"), "text")


def shopify_metafield_type(data_type: str) -> str:
    return SHOPIFY_METAFIELD_TYPE.get(str(data_type or "text"), "single_line_text_field")


def channel_compatibility(data_type: str, channel: str, representation: dict[str, Any] | None = None) -> str:
    """ok | incompatible | unresolved."""
    canonical = map_canonical_data_type(data_type)
    payload = representation or {}
    channel_key = str(channel or "").strip().lower()
    channel_attr = str(
        payload.get("channel_attribute_code")
        or payload.get("attribute_code")
        or payload.get("key")
        or ""
    ).strip().lower()
    if channel_key == "magento":
        if channel_attr in {"weight"} and canonical in {"decimal", "integer", "text"}:
            return "ok"
        expected = magento_frontend_input(canonical)
        actual = str(payload.get("frontend_input") or payload.get("channel_frontend_input") or "").strip().lower()
        if not actual and not payload.get("channel_attribute_code"):
            return "unresolved"
        if actual and actual != expected and not _magento_compatible(canonical, actual):
            return "incompatible"
        return "ok" if payload.get("channel_attribute_code") or actual else "unresolved"
    if channel_key == "shopify":
        if channel_attr in {"weight", "weight_unit"} and canonical in {"decimal", "integer", "text"}:
            return "ok"
        expected = shopify_metafield_type(canonical)
        actual = str(payload.get("metafield_type") or payload.get("data_type") or "").strip().lower()
        if not actual and not payload.get("channel_attribute_code") and not payload.get("key"):
            return "unresolved"
        if actual and actual != expected and not _shopify_compatible(canonical, actual):
            return "incompatible"
        return "ok"
    return "unresolved"


def _magento_compatible(canonical: str, frontend_input: str) -> bool:
    if canonical in SELECTABLE_TYPES and frontend_input in {"select", "multiselect", "swatch"}:
        return canonical == "multiselect" or frontend_input != "multiselect"
    if canonical in {"text", "textarea", "html"} and frontend_input in {"text", "textarea", "weight"}:
        return True
    if canonical in {"integer", "decimal"} and frontend_input in {"text", "price", "weight"}:
        return True
    return frontend_input == magento_frontend_input(canonical)


def _shopify_compatible(canonical: str, metafield_type: str) -> bool:
    if canonical == "multiselect":
        return metafield_type.startswith("list.")
    if canonical in {"text", "select"} and metafield_type in {"single_line_text_field", "list.single_line_text_field"}:
        return True
    if canonical in {"integer", "decimal"} and metafield_type in {
        "number_decimal",
        "number_integer",
        "weight",
        "dimension",
        "volume",
        "single_line_text_field",
    }:
        return True
    return metafield_type == shopify_metafield_type(canonical)
