"""
Mapeo fila CSV → datos para CustomsBroker.
Clarion: TIPO normalizado a M/A con parse_tipo_agente_aduanal; CURP/personal_id máx 19.
"""
from typing import Dict, Any, Optional

from .common_validators import parse_tipo_agente_aduanal, CURP_MAX, normalize_phone_digits

MAX_LEN = {
    "broker_key": 5,
    "type": 9,
    "name": 80,
    "address": 1500,
    "postal_code": 15,
    "city": 30,
    "state": 30,
    "phone": 30,
    "fax": 30,
    "email": 100,
    "country": 3,
    "tax_id": 30,
    "personal_id": 20,
    "position": 30,
    "license": 4,
    "company": 200,
    "contact": 80,
}


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 _license_value(row_norm: Dict[str, Any]) -> Optional[str]:
    lic = (row_norm.get("LICENCIA") or "").strip()
    if not lic or not lic.isdigit():
        return None
    return lic[:4]


def row_to_customs_broker_data(
    row_norm: Dict[str, Any], tenant_id: int, company_id: int
) -> Dict[str, Any]:
    """Build dict for CustomsBroker model (create or update)."""
    clave = _str_or_none(row_norm.get("CLAVE"), MAX_LEN["broker_key"])
    if not clave:
        return {}
    tipo_raw = (row_norm.get("TIPO") or "").strip()
    tipo_normalized = parse_tipo_agente_aduanal(tipo_raw) if tipo_raw else None
    return {
        "tenant_id": tenant_id,
        "company_id": company_id,
        "broker_key": clave,
        "type": tipo_normalized or _str_or_none(row_norm.get("TIPO"), MAX_LEN["type"]),
        "name": _str_or_none(row_norm.get("NOMBRE"), MAX_LEN["name"]),
        "address": _str_or_none(row_norm.get("DIRECCION"), MAX_LEN["address"]),
        "postal_code": _str_or_none(row_norm.get("CODIGO POSTAL"), MAX_LEN["postal_code"]),
        "city": _str_or_none(row_norm.get("CIUDAD"), MAX_LEN["city"]),
        "state": _str_or_none(row_norm.get("ESTADO"), MAX_LEN["state"]),
        "phone": _str_or_none(normalize_phone_digits(row_norm.get("TELEFONO")), MAX_LEN["phone"]),
        "fax": _str_or_none(row_norm.get("FAX"), MAX_LEN["fax"]),
        "email": _str_or_none(row_norm.get("EMAIL"), MAX_LEN["email"]),
        "country": _str_or_none(row_norm.get("PAIS"), MAX_LEN["country"]),
        "tax_id": _str_or_none(row_norm.get("RFC"), MAX_LEN["tax_id"]),
        "personal_id": _str_or_none(row_norm.get("PERSONAL_ID"), CURP_MAX),
        "position": _str_or_none(row_norm.get("POSICION"), MAX_LEN["position"]),
        "license": _license_value(row_norm),
        "company": _str_or_none(row_norm.get("EMPRESA"), MAX_LEN["company"]),
        "contact": _str_or_none(row_norm.get("CONTACTO"), MAX_LEN["contact"]),
    }
