"""
Validaciones comunes de fila para import CSV de vehículos.
Paridad Clarion: VALIDACIONES_TRANSPORTE, VALIDA_TODA_TRANSPORTE, VALIDA_PARCIAL_TRANSPORTE.
"""
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_codigo_entidad_required,
    check_transport_type_catalog,
    check_pais_catalog_vehicles,
    check_estado_catalog,
    check_estado_pais_consistency,
)


def validate_row_vehicle_required(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    return check_required(row, "CLAVE", MAX_LEN["vehicle_key"], line_num)


def validate_row_vehicle_lengths(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    checks = [
        ("CLAVE ACE", MAX_LEN["ace_vehicle_key"]),
        ("CLAVE TRANSPORTE", MAX_LEN["transporter_key"]),
        ("VIN", MAX_LEN["series"]),
        ("TIPO TRANSPORTE", MAX_LEN["transport_type"]),
        ("CODIGO DE ENTIDAD", MAX_LEN["entity_code"]),
        ("TRANSPONDEDOR", MAX_LEN["transponder_number"]),
        ("NUMERO DOT", MAX_LEN["dot_number"]),
        ("PLACAS", MAX_LEN["plate_number"]),
        ("CIUDAD", MAX_LEN["city"]),
        ("ESTADO", MAX_LEN["state"]),
        ("PAIS", MAX_LEN["country"]),
        ("PRECINTO", MAX_LEN["seal"]),
        ("EMPRESA ASEGURADORA", MAX_LEN["insurance_company_name"]),
        ("NUM. ASEGURADORA", MAX_LEN["insurance_number"]),
    ]
    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_vehicle_amount(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    from ..common.common_validators import parse_decimal
    monto = row.get("MONTO ASEGURADO") or row.get("MONTO")
    if monto is None or not str(monto).strip():
        return None
    if parse_decimal(monto) is None:
        return {"line": line_num, "col": "MONTO ASEGURADO", "msg": "Debe ser numérico"}
    return None


def validate_row_vehicle_insurance_date(row: Dict[str, Any], line_num: int) -> Optional[Dict[str, Any]]:
    from ..common.common_validators import parse_insurance_date
    fecha = row.get("FECHA DE ASEGURADORA") or row.get("FECHA ASEGURADORA")
    if fecha is None or not str(fecha).strip():
        return None
    if parse_insurance_date(fecha) is None:
        return {"line": line_num, "col": "FECHA DE ASEGURADORA", "msg": "Formato de fecha inválido (use YYYYMMDD o DD/MM/YYYY)"}
    return None


def validaciones_transporte(
    row: Dict[str, Any],
    line_num: int,
    valid_transport_codes: 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,
) -> List[Dict[str, Any]]:
    """
    VALIDACIONES_TRANSPORTE: reglas compartidas (longitudes, tipo transporte, código entidad dominio,
    país, estado, estado-país). No exige CODIGO DE ENTIDAD obligatorio (eso es solo VALIDA_TODA).
    """
    errors: List[Dict[str, Any]] = []
    for err in [
        validate_row_vehicle_lengths(row, line_num),
        validate_row_vehicle_amount(row, line_num),
        validate_row_vehicle_insurance_date(row, line_num),
        check_codigo_entidad_valores(row, line_num),
        check_transport_type_catalog(row, line_num, valid_transport_codes),
        check_pais_catalog_vehicles(row, line_num, valid_country_ame),
        check_estado_catalog(row, line_num, state_descriptions_upper),
        check_estado_pais_consistency(row, line_num, state_country_set),
    ]:
        if err:
            errors.append(err)
    return errors


def valida_toda_transporte(
    row: Dict[str, Any],
    line_num: int,
    valid_transport_codes: 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,
) -> List[Dict[str, Any]]:
    """VALIDA_TODA_TRANSPORTE: CODIGO DE ENTIDAD obligatorio + VALIDACIONES_TRANSPORTE (registro nuevo)."""
    errors: List[Dict[str, Any]] = []
    err = check_codigo_entidad_required(row, line_num)
    if err:
        errors.append(err)
    errors.extend(
        validaciones_transporte(
        row, line_num,
        valid_transport_codes=valid_transport_codes,
        valid_country_ame=valid_country_ame,
        state_descriptions_upper=state_descriptions_upper,
        state_country_set=state_country_set,
        )
    )
    return errors


def valida_parcial_transporte(
    row: Dict[str, Any],
    line_num: int,
    valid_transport_codes: 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,
) -> List[Dict[str, Any]]:
    """VALIDA_PARCIAL_TRANSPORTE: solo VALIDACIONES_TRANSPORTE (actualizar registro existente)."""
    return validaciones_transporte(
        row, line_num,
        valid_transport_codes=valid_transport_codes,
        valid_country_ame=valid_country_ame,
        state_descriptions_upper=state_descriptions_upper,
        state_country_set=state_country_set,
    )
