"""
Configuración de plantilla CSV para Vehículos / Transportes (EstructuraCatTransportes.xls).
Mapeo: CLAVE → vehicle_key, CLAVE ACE → ace_vehicle_key, etc.
"""

from typing import Dict, List, Any

from ..common.cell_value import cell_to_str

TEMPLATE_COLUMNS: Dict[str, List[Dict[str, Any]]] = {
    "vehicles": [
        {"canonical": "CLAVE", "aliases": ["CLAVE VEHICULO", "VEHICLE KEY", "KEY"]},
        {"canonical": "CLAVE ACE", "aliases": ["ACE", "CLAVEACE"]},
        {"canonical": "CLAVE TRANSPORTE", "aliases": ["TRANSPORTE", "TRANSPORTISTA"]},
        {"canonical": "VIN", "aliases": ["SERIE", "SERIES", "NUMERO SERIE"]},
        {"canonical": "TIPO TRANSPORTE", "aliases": ["TIPO", "TRANSPORT TYPE"]},
        {"canonical": "CODIGO DE ENTIDAD", "aliases": ["ENTIDAD", "ENTITY CODE"]},
        {"canonical": "TRANSPONDEDOR", "aliases": ["TRANSPONDER", "TRANSPONDER NUMBER"]},
        {"canonical": "NUMERO DOT", "aliases": ["DOT", "NUM DOT"]},
        {"canonical": "PLACAS", "aliases": ["PLACA", "PLATE", "PLATE NUMBER"]},
        {"canonical": "CIUDAD", "aliases": ["CITY"]},
        {"canonical": "ESTADO", "aliases": ["STATE"]},
        {"canonical": "PAIS", "aliases": ["COUNTRY", "Pais"]},
        {"canonical": "PRECINTO", "aliases": ["SEAL"]},
        {"canonical": "EMPRESA ASEGURADORA", "aliases": ["ASEGURADORA", "INSURANCE COMPANY"]},
        {"canonical": "NUM. ASEGURADORA", "aliases": ["NUM ASEGURADORA", "POLIZA", "INSURANCE NUMBER"]},
        {"canonical": "MONTO ASEGURADO", "aliases": ["MONTO", "INSURANCE AMOUNT"]},
        {"canonical": "FECHA DE ASEGURADORA", "aliases": ["FECHA ASEGURADORA", "INSURANCE DATE"]},
        {"canonical": "COL_EXTRA", "aliases": ["COLUMNA R", "COL R"]},
    ],
}


def build_normalized_lookup(normalize_header_fn) -> Dict[str, str]:
    cols = TEMPLATE_COLUMNS.get("vehicles")
    if not cols:
        return {}
    lookup: Dict[str, str] = {}
    for item in cols:
        canonical = item["canonical"]
        lookup[normalize_header_fn(canonical)] = canonical
        for alias in item.get("aliases") or []:
            lookup[normalize_header_fn(alias)] = canonical
    return lookup


def row_from_template(row: Dict[str, Any], normalize_header_fn) -> Dict[str, Any]:
    lookup = build_normalized_lookup(normalize_header_fn)
    if not lookup:
        return {normalize_header_fn(k): cell_to_str(v) for k, v in row.items()}
    out: Dict[str, Any] = {}
    for csv_header, value in row.items():
        key_norm = normalize_header_fn(csv_header)
        if key_norm in lookup:
            out[lookup[key_norm]] = cell_to_str(value)
    return out
