"""
Mapeo fila CSV → datos para Driver (conductores).
Clarion: FORMA IDENTIFICACION 1/2 se guardan expandidas (ACW → ACW-Pasaporte, etc.).
"""
from typing import Dict, Any, Optional

from .common_validators import (
    MAX_LEN,
    parse_int,
    parse_birth_date,
    FORMA_IDENTIFICACION_MAP,
)


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 _forma_identificacion_or_raw(val: Any, max_len: int) -> Optional[str]:
    """Si el valor es una clave Clarion (ACW, ALR, ...), devuelve el valor expandido; si no, el valor truncado."""
    s = _str_or_none(val, max_len)
    if not s:
        return None
    expanded = FORMA_IDENTIFICACION_MAP.get(s.upper())
    if expanded:
        return expanded[:max_len] if len(expanded) > max_len else expanded
    return s


def row_to_driver_data(
    row_norm: Dict[str, Any],
    tenant_id: int,
    company_id: int,
) -> Dict[str, Any]:
    """Mapea una fila normalizada del CSV a un diccionario para DriverCreateDTO."""
    transporter_key = _str_or_none(row_norm.get("TRANSPORTISTA"), MAX_LEN["transporter_key"])
    line = parse_int(row_norm.get("LINEA"))
    if not transporter_key or line is None:
        return {}
    return {
        "transporter_key": transporter_key,
        "line": line,
        "driver_name": _str_or_none(row_norm.get("CLAVE CONDUCTOR"), MAX_LEN["driver_name"]),
        "license_number": _str_or_none(row_norm.get("LICENCIA"), MAX_LEN["license_number"]),
        "express_line_id": _str_or_none(row_norm.get("PERMISO LINEA EXPRESS"), MAX_LEN["express_line_id"]),
        "ace_id": _str_or_none(row_norm.get("IDENTIFICACION ACE"), MAX_LEN["ace_id"]),
        "birth_date": parse_birth_date(row_norm.get("FECHA NACIMIENTO")),
        "gender": _str_or_none(row_norm.get("SEXO"), MAX_LEN["gender"]),
        "birth_country": _str_or_none(row_norm.get("PAIS NACIMIENTO"), MAX_LEN["birth_country"]),
        "hazardous_material_auth": _str_or_none(
            row_norm.get("TRANSPORTA MAT. PELIGROSO?"), MAX_LEN["hazardous_material_auth"]
        ),
        "hazardous_material_state": _str_or_none(
            row_norm.get("PERMISO MAT. PELIGROSO"), MAX_LEN["hazardous_material_state"]
        ),
        "first_name": _str_or_none(row_norm.get("NOMBRE(S)"), MAX_LEN["first_name"]),
        "last_name": _str_or_none(row_norm.get("APELLIDO PATERNO"), MAX_LEN["last_name"]),
        "id_key1": _forma_identificacion_or_raw(
            row_norm.get("FORMA IDENTIFICACION 1"), MAX_LEN["id_key1"]
        ),
        "id_number1": _str_or_none(row_norm.get("NUM. IDENTIFICACION 1"), MAX_LEN["id_number1"]),
        "id_state1": _str_or_none(row_norm.get("ESTADO"), MAX_LEN["id_state1"]),
        "id_country1": _str_or_none(row_norm.get("PAIS"), MAX_LEN["id_country1"]),
        "id_key2": _forma_identificacion_or_raw(
            row_norm.get("FORMA IDENTIFICACION 2"), MAX_LEN["id_key2"]
        ),
        "id_number2": _str_or_none(row_norm.get("NUM. IDENTIFICACION 2"), MAX_LEN["id_number2"]),
        "id_state2": _str_or_none(row_norm.get("ESTADO 2"), MAX_LEN["id_state2"]),
        "id_country2": _str_or_none(row_norm.get("PAIS 2"), MAX_LEN["id_country2"]),
        "company_id": company_id,
        "tenant_id": tenant_id,
    }
