"""Helpers for inventory vs non-inventory (service) products."""
from __future__ import annotations

from typing import Any, Mapping, Optional, Union

# Product types that are sold but never stock-tracked (no qty, allocations, or deductions).
NON_INVENTORY_PRODUCT_TYPES = frozenset(
    {
        "service",
        "non_inventory",
        "labor",
        "consultation",
    }
)

ProductLike = Union[Mapping[str, Any], Any]


def normalize_product_type(product_type: Optional[str]) -> str:
    pt = (product_type or "inventory_item").strip().lower()
    if pt in {"non-inventory", "noninventory"}:
        return "non_inventory"
    return pt or "inventory_item"


def is_inventory_tracked(product: Optional[ProductLike]) -> bool:
    """True when product participates in quantity / branch stock logic."""
    if product is None:
        return True
    if isinstance(product, Mapping):
        pt = normalize_product_type(product.get("product_type"))
    else:
        pt = normalize_product_type(getattr(product, "product_type", None))
    return pt not in NON_INVENTORY_PRODUCT_TYPES


def apply_non_inventory_defaults(data: dict) -> dict:
    """Normalize payload when creating/updating a service or non-stock item."""
    pt = normalize_product_type(data.get("product_type"))
    data["product_type"] = pt
    if is_inventory_tracked({"product_type": pt}):
        return data
    data["quantity"] = 0
    data["minimum_stock_level"] = 0
    data["reorder_point"] = 0
    data["maximum_stock_level"] = None
    data["is_serialized"] = False
    data["is_weight_based"] = False
    data["is_perishable"] = False
    return data
