"""
Validaciones comunes de fila para import CSV de conductores.
Paridad Clarion: VALIDACIONES_CONDUCTOR, VALIDA_TODA_CONDUCTOR, VALIDA_PARCIAL_CONDUCTOR.
"""
from typing import Dict, Any, Optional, Set, List

from ..common.common_validators import (
    MAX_LEN,
    check_max_length,
    check_int_positive,
    check_optional_birth_date,
    check_transportista_catalog,
    check_sexo_m_f,
    check_pais_catalog_drivers,
    check_material_peligroso_si_no,
    check_tipo_identificacion,
)


def validate_row_driver_required(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    """Obligatorios Clarion: Col A (TRANSPORTISTA) y Col C (CLAVE CONDUCTOR). Si falta uno, no se ejecutan validaciones."""
    err = check_max_length(
        row, "TRANSPORTISTA", MAX_LEN["transporter_key"], line_num, required=True
    )
    if err:
        return err
    err = check_max_length(
        row, "CLAVE CONDUCTOR", MAX_LEN["driver_name"], line_num, required=True
    )
    if err:
        return err
    return None


def validate_row_driver_required_full(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    """VALIDA_TODA: obligatorios A, C y LINEA (Col B) para registro nuevo."""
    err = validate_row_driver_required(row, line_num)
    if err:
        return err
    return check_int_positive(row, "LINEA", line_num)


def validate_row_driver_lengths(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    checks = [
        ("CLAVE CONDUCTOR", MAX_LEN["driver_name"]),
        ("LICENCIA", MAX_LEN["license_number"]),
        ("PERMISO LINEA EXPRESS", MAX_LEN["express_line_id"]),
        ("IDENTIFICACION ACE", MAX_LEN["ace_id"]),
        ("SEXO", MAX_LEN["gender"]),
        ("PAIS NACIMIENTO", MAX_LEN["birth_country"]),
        ("TRANSPORTA MAT. PELIGROSO?", MAX_LEN["hazardous_material_auth"]),
        ("PERMISO MAT. PELIGROSO", MAX_LEN["hazardous_material_state"]),
        ("NOMBRE(S)", MAX_LEN["first_name"]),
        ("APELLIDO PATERNO", MAX_LEN["last_name"]),
        ("FORMA IDENTIFICACION 1", MAX_LEN["id_key1"]),
        ("NUM. IDENTIFICACION 1", MAX_LEN["id_number1"]),
        ("ESTADO", MAX_LEN["id_state1"]),
        ("PAIS", MAX_LEN["id_country1"]),
        ("FORMA IDENTIFICACION 2", MAX_LEN["id_key2"]),
        ("NUM. IDENTIFICACION 2", MAX_LEN["id_number2"]),
        ("ESTADO 2", MAX_LEN["id_state2"]),
        ("PAIS 2", MAX_LEN["id_country2"]),
    ]
    for col, max_len in checks:
        err = check_max_length(row, col, max_len, line_num)
        if err:
            return err
    return None


def validate_row_driver_date(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    return check_optional_birth_date(row, "FECHA NACIMIENTO", line_num)


def validaciones_conductores(
    row: Dict[str, Any],
    line_num: int,
    valid_transporter_keys: Optional[Set[str]] = None,
    valid_country_ame: Optional[Set[str]] = None,
) -> List[Dict[str, Any]]:
    """
    VALIDACIONES_CONDUCTOR: reglas compartidas (longitudes, fecha, transportista en catálogo,
    sexo M/F, país nacimiento, material peligroso Si/No, tipo ID 1/2, país ID1/ID2).
    """
    errors: List[Dict[str, Any]] = []
    for err in [
        validate_row_driver_lengths(row, line_num),
        validate_row_driver_date(row, line_num),
        check_transportista_catalog(row, line_num, valid_transporter_keys),
        check_sexo_m_f(row, line_num),
        check_pais_catalog_drivers(
            row, "PAIS NACIMIENTO", line_num, valid_country_ame, col_letter="Col. I"
        ),
        check_material_peligroso_si_no(row, line_num),
        check_tipo_identificacion(
            row,
            "FORMA IDENTIFICACION 1",
            line_num,
            col_letter="Col. N",
            primera_o_segunda="Primera",
        ),
        check_pais_catalog_drivers(
            row, "PAIS", line_num, valid_country_ame, col_letter="Col. Q"
        ),
        check_tipo_identificacion(
            row,
            "FORMA IDENTIFICACION 2",
            line_num,
            col_letter="Col. R",
            primera_o_segunda="Segunda",
        ),
        check_pais_catalog_drivers(
            row, "PAIS 2", line_num, valid_country_ame, col_letter="Col. U"
        ),
    ]:
        if err:
            errors.append(err)

    return errors


def valida_toda_conductor(
    row: Dict[str, Any],
    line_num: int,
    valid_transporter_keys: Optional[Set[str]] = None,
    valid_country_ame: Optional[Set[str]] = None,
) -> List[Dict[str, Any]]:
    """VALIDA_TODA_CONDUCTOR: obligatorios A, C y LINEA (B) + validaciones_conductores (registro nuevo)."""
    errors: List[Dict[str, Any]] = []
    err = validate_row_driver_required_full(row, line_num)
    if err:
        errors.append(err)
    errors.extend(
        validaciones_conductores(
        row, line_num,
        valid_transporter_keys=valid_transporter_keys,
        valid_country_ame=valid_country_ame,
        )
    )
    return errors


def valida_parcial_conductor(
    row: Dict[str, Any],
    line_num: int,
    valid_transporter_keys: Optional[Set[str]] = None,
    valid_country_ame: Optional[Set[str]] = None,
) -> List[Dict[str, Any]]:
    """VALIDA_PARCIAL_CONDUCTOR: solo validaciones_conductores (actualizar registro existente)."""
    return validaciones_conductores(
        row, line_num,
        valid_transporter_keys=valid_transporter_keys,
        valid_country_ame=valid_country_ame,
    )
