"""
Mapeo fila CSV → datos para BOM (para cuando exista tabla BOM).
"""
from decimal import Decimal, InvalidOperation
from typing import Dict, Any, Optional, Set


def _decimal_or_none(val: Any) -> Optional[Decimal]:
    if val is None or val == "":
        return None
    try:
        return Decimal(str(val).replace(",", "."))
    except (InvalidOperation, ValueError, TypeError):
        return None


def _str_or_none(val: Any, max_len: Optional[int] = None) -> Optional[str]:
    if val is None:
        return None
    s = str(val).strip()
    if not s:
        return None
    if max_len and len(s) > max_len:
        return s[:max_len]
    return s


def row_to_bom_data(
    row_norm: Dict[str, Any],
    valid_part_numbers: Set[str],
) -> Dict[str, Any]:
    """
    Mapea una fila normalizada del CSV a un diccionario de datos para BOM.
    Para uso futuro cuando exista tabla BOM.
    """
    parent = _str_or_none(row_norm.get("NUMPARTE_PADRE"), 70)
    component = _str_or_none(row_norm.get("NUMPARTE_COMPONENTE"), 70)
    quantity = _decimal_or_none(row_norm.get("CANTIDAD"))
    uom = _str_or_none(row_norm.get("UNIMED"), 10)
    version_bom = _decimal_or_none(row_norm.get("VERSION_BOM"))
    version_bill = _decimal_or_none(row_norm.get("VERSION_BILL"))
    return {
        "parent_part_number": parent,
        "component_part_number": component,
        "quantity": quantity,
        "uom": uom,
        "version_bom": version_bom,
        "version_bill": version_bill,
    }
