"""
Validaciones comunes de fila para import CSV de trailers.
Paridad Clarion: VALIDACIONES_TRAILER, VALIDA_TODA_TRAILER, VALIDA_PARCIAL_TRAILER.
"""
from typing import Dict, Any, Optional, Set, Tuple, List

from ..common.common_validators import (
    MAX_LEN,
    check_required,
    check_max_length,
    check_codigo_entidad_valores,
    check_trailer_type_catalog,
    check_pais_catalog_trailers,
    check_estado_catalog_trailers,
    check_estado_pais_consistency_trailers,
)


def validate_row_trailer_required(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    return check_required(row, "NUMERO TRAILER", MAX_LEN["trailer_number"], line_num)


def validate_row_trailer_lengths(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    checks = [
        ("CLAVE ACE", MAX_LEN["ace_trailer_number"]),
        ("TIPO TRAILER", MAX_LEN["trailer_type_key"]),
        ("PRECINTO", MAX_LEN["seal"]),
        ("CODIGO ENTIDAD", MAX_LEN["entity_code"]),
        ("CODIGO DE ENTIDAD", MAX_LEN["entity_code"]),
        ("PLACAS", MAX_LEN["plate_number"]),
        ("ESTADO", MAX_LEN["state"]),
        ("PAIS", MAX_LEN["country"]),
        ("CLAVE CONTENEDOR", MAX_LEN["container_key"]),
    ]
    for col, max_len in checks:
        err = check_max_length(row, col, max_len, line_num)
        if err:
            return err
    return None


def validaciones_trailer(
    row: Dict[str, Any],
    line_num: int,
    valid_trailer_type_keys: Optional[Set[str]] = None,
    valid_country_ame: Optional[Set[str]] = None,
    state_descriptions_upper: Optional[Set[str]] = None,
    state_country_set: Optional[Set[Tuple[str, str]]] = None,
    state_ame_to_description: Optional[Dict[str, str]] = None,
) -> List[Dict[str, Any]]:
    """
    VALIDACIONES_TRAILER: reglas compartidas (longitudes, tipo trailer, código entidad,
    país, estado, estado-país). No exige CODIGO DE ENTIDAD obligatorio.
    """
    errors: List[Dict[str, Any]] = []

    err = validate_row_trailer_required(row, line_num)
    if err:
        errors.append(err)

    err = validate_row_trailer_lengths(row, line_num)
    if err:
        errors.append(err)

    err = check_codigo_entidad_valores(row, line_num)
    if err:
        errors.append(err)

    err = check_trailer_type_catalog(row, line_num, valid_trailer_type_keys)
    if err:
        errors.append(err)

    err = check_pais_catalog_trailers(row, line_num, valid_country_ame)
    if err:
        errors.append(err)

    err_estado, estado_resuelto_upper = check_estado_catalog_trailers(
        row, line_num, state_descriptions_upper, state_ame_to_description
    )
    if err_estado:
        errors.append(err_estado)

    err = check_estado_pais_consistency_trailers(
        row, line_num, state_country_set, estado_resuelto_upper
    )
    if err:
        errors.append(err)

    return errors


def valida_toda_trailer(
    row: Dict[str, Any],
    line_num: int,
    valid_trailer_type_keys: Optional[Set[str]] = None,
    valid_country_ame: Optional[Set[str]] = None,
    state_descriptions_upper: Optional[Set[str]] = None,
    state_country_set: Optional[Set[Tuple[str, str]]] = None,
    state_ame_to_description: Optional[Dict[str, str]] = None,
) -> List[Dict[str, Any]]:
    """VALIDA_TODA_TRAILER: mismo que validaciones_trailer (Col A ya validada antes)."""
    return validaciones_trailer(
        row,
        line_num,
        valid_trailer_type_keys=valid_trailer_type_keys,
        valid_country_ame=valid_country_ame,
        state_descriptions_upper=state_descriptions_upper,
        state_country_set=state_country_set,
        state_ame_to_description=state_ame_to_description,
    )


def valida_parcial_trailer(
    row: Dict[str, Any],
    line_num: int,
    valid_trailer_type_keys: Optional[Set[str]] = None,
    valid_country_ame: Optional[Set[str]] = None,
    state_descriptions_upper: Optional[Set[str]] = None,
    state_country_set: Optional[Set[Tuple[str, str]]] = None,
    state_ame_to_description: Optional[Dict[str, str]] = None,
) -> List[Dict[str, Any]]:
    """VALIDA_PARCIAL_TRAILER: solo validaciones_trailer (actualizar registro existente)."""
    return validaciones_trailer(
        row,
        line_num,
        valid_trailer_type_keys=valid_trailer_type_keys,
        valid_country_ame=valid_country_ame,
        state_descriptions_upper=state_descriptions_upper,
        state_country_set=state_country_set,
        state_ame_to_description=state_ame_to_description,
    )
