"""
Configuracion de plantilla CSV para Conductores (EstructuraCatConductor.xls).
"""

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, merge_enum_hint_before_max
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 DRIVERS_CSV_MAX_CHARS

TEMPLATE_COLUMNS: Dict[str, List[Dict[str, Any]]] = {
    "drivers": [
        {"canonical": "TRANSPORTISTA", "aliases": ["TRANSPORTISTA CLAVE", "CLAVE TRANSPORTISTA", "TRANSPORTER"]},
        {"canonical": "LINEA", "aliases": ["LINE", "LINEA CONDUCTOR"]},
        {"canonical": "CLAVE CONDUCTOR", "aliases": ["CONDUCTOR", "DRIVER", "NOMBRE CONDUCTOR"]},
        {"canonical": "LICENCIA", "aliases": ["LICENSE", "LICENCE"]},
        {"canonical": "PERMISO LINEA EXPRESS", "aliases": ["LINEA EXPRESS", "LINEA EXPRESS ID", "EXPRESS LINE"]},
        {"canonical": "IDENTIFICACION ACE", "aliases": ["ACE", "ACE ID", "IDENTIFICACION ACE ID"]},
        {"canonical": "FECHA NACIMIENTO", "aliases": ["FECHA NAC", "BIRTH DATE", "BIRTHDATE"]},
        {"canonical": "SEXO", "aliases": ["GENERO", "GENDER"]},
        {"canonical": "PAIS NACIMIENTO", "aliases": ["PAIS Nacimiento", "BIRTH COUNTRY"]},
        {"canonical": "TRANSPORTA MAT. PELIGROSO?", "aliases": ["MATERIAL PELIGROSO", "HAZMAT", "HAZARDOUS MATERIAL"]},
        {"canonical": "PERMISO MAT. PELIGROSO", "aliases": ["PERMISO MAT PELIGROSO", "HAZMAT PERMIT"]},
        {"canonical": "NOMBRE(S)", "aliases": ["NOMBRE", "NOMBRES", "FIRST NAME"]},
        {"canonical": "APELLIDO PATERNO", "aliases": ["APELLIDO", "LAST NAME", "APELLIDO P"]},
        {"canonical": "FORMA IDENTIFICACION 1", "aliases": ["FORMA IDENTIFICACION", "ID TIPO 1", "ID KEY 1"]},
        {"canonical": "NUM. IDENTIFICACION 1", "aliases": ["NUM IDENTIFICACION 1", "ID NUMERO 1", "ID NUMBER 1"]},
        {"canonical": "ESTADO", "aliases": ["ESTADO 1", "STATE 1"]},
        {"canonical": "PAIS", "aliases": ["PAIS 1", "COUNTRY 1"]},
        {"canonical": "FORMA IDENTIFICACION 2", "aliases": ["ID TIPO 2", "ID KEY 2"]},
        {"canonical": "NUM. IDENTIFICACION 2", "aliases": ["NUM IDENTIFICACION 2", "ID NUMERO 2", "ID NUMBER 2"]},
        {"canonical": "ESTADO 2", "aliases": ["STATE 2"]},
        {"canonical": "PAIS 2", "aliases": ["COUNTRY 2"]},
        {"canonical": "COL_EXTRA", "aliases": ["COLUMNA V", "COL V"]},
    ],
}

inject_en_labels_into_template_columns(TEMPLATE_COLUMNS)

inject_max_char_hints_into_columns(TEMPLATE_COLUMNS.get("drivers"), DRIVERS_CSV_MAX_CHARS)
for _dc in TEMPLATE_COLUMNS.get("drivers") or []:
    c = _dc.get("canonical")
    if c == "SEXO":
        merge_enum_hint_before_max(_dc, ["M", "F"])
    elif c == "TRANSPORTA MAT. PELIGROSO?":
        merge_enum_hint_before_max(_dc, ["SI", "NO"])


def build_normalized_lookup(normalize_header_fn) -> Dict[str, str]:
    cols = TEMPLATE_COLUMNS.get("drivers")
    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
