"""
Configuración de plantilla CSV para Transportistas (EstructuraCatTransportistas).
Mapeo Clarion: Col A = CLAVE TRANSPORTISTA, B = NOMBRE, ... R = DIRECTORIO FTP, S = desfase.
"""

from typing import Dict, List, Any

from ..common.cell_value import cell_to_str
from ..common.csv_hint_inject import inject_max_char_hints_into_columns
from ..common.inject_csv_labels_en import inject_en_labels_into_template_columns
from ..common.template_locale import merge_download_header_into_lookup, merge_labels_into_lookup
from .csv_max_chars_for_headers import TRANSPORTISTAS_CSV_MAX_CHARS

TEMPLATE_COLUMNS: Dict[str, List[Dict[str, Any]]] = {
    "transporters": [
        {"canonical": "CLAVE TRANSPORTISTA", "aliases": ["TRANSPORTISTA", "CLAVE TRANS", "CARRIER KEY"]},
        {"canonical": "NOMBRE", "aliases": ["NOMBRE TRANSPORTISTA", "NAME"]},
        {"canonical": "NOMBRE CORTO", "aliases": ["NOMBRE CORTO TRANS", "SHORT NAME"]},
        {"canonical": "RESPONSABLE", "aliases": ["RESPONSABLE TRANS"]},
        {"canonical": "RFC", "aliases": ["RFC TRANS"]},
        {"canonical": "CALLES", "aliases": ["STREETS", "DIRECCION"]},
        {"canonical": "CODIGO POSTAL", "aliases": ["CODIGO POSTAL TRANS", "POSTAL CODE", "CP"]},
        {"canonical": "CIUDAD", "aliases": ["CITY", "CIUDAD TRANS"]},
        {"canonical": "ESTADO", "aliases": ["STATE", "ESTADO TRANS"]},
        {"canonical": "PAIS", "aliases": ["COUNTRY", "PAIS TRANS"]},
        {"canonical": "CODIGO CARGADOR", "aliases": ["COD CARGADOR", "LOADER CODE"]},
        {"canonical": "CODIGO CAAT", "aliases": ["CAAT", "CODIGO CAAT TRANS"]},
        {"canonical": "CODIGO TRANS", "aliases": ["COD TRANS", "TRANSPORT CODE", "SCAC"]},
        {"canonical": "TIPO INTERFASE TRANS", "aliases": ["TIPO INTERFASE", "INTERFACE TYPE"]},
        {"canonical": "SERVIDOR FTP", "aliases": ["FTP SERVER", "SERVIDOR FTP TRANS"]},
        {"canonical": "USUARIO FTP", "aliases": ["FTP USER", "USUARIO FTP TRANS"]},
        {"canonical": "CLAVE ACCESO FTP", "aliases": ["CLAVE FTP", "FTP PASSWORD", "PASSWORD FTP"]},
        {"canonical": "DIRECTORIO FTP", "aliases": ["FTP DIRECTORY", "DIRECTORIO FTP TRANS"]},
        {"canonical": "COL_EXTRA", "aliases": ["COLUMNA S", "COL S", "COL 19"]},
    ],
}

inject_en_labels_into_template_columns(TEMPLATE_COLUMNS)

inject_max_char_hints_into_columns(
    TEMPLATE_COLUMNS.get("transporters"), TRANSPORTISTAS_CSV_MAX_CHARS
)


def build_normalized_lookup(normalize_header_fn) -> Dict[str, str]:
    cols = TEMPLATE_COLUMNS.get("transporters")
    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
        merge_labels_into_lookup(item, canonical, normalize_header_fn, lookup)
        merge_download_header_into_lookup(item, canonical, normalize_header_fn, lookup)
    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
