"""
Configuración de plantilla CSV para Clientes y Proveedores (EstructuraCatClienteProv.xls).
Layout Clarion: Col A = PROCEDENCIA (E/N), B = TIPO (C/P/A), C = CLAVE (máx 8), D = NOMBRE, E = RFC, F–AG.
Solo se leen columnas definidas aquí; el resto se ignora.
Correspondencia Clarion → canonical: A=PROCEDENCIA, B=TIPO, C=SHORT_NAME, D=NOMBRE, E=RFC, F=CALLES(DIRECCION),
G=NUM_EXT, H=CODIGO POSTAL, I=COLONIA, J=CIUDAD, K=ESTADO, L=PAIS, M=TELEFONO, N=FAX, O=EMAIL, P=CURP,
Q=TIPO_PROGRAMA_SECON, R=NUM_PROGRAMA_SECON, S=FECHA_AUT_SECON, T=ES_PROSEC, U=NUM_AUT_PROSEC, V=VINCULACION,
W=ES_EMPRESA_CERTIFICADA, X=REGISTRO_EMPRESA_CERT, Y=INFORMACION_EXTRA, Z=CONTACTO, AA=MANUFACTURER_ID,
AB=TAX_ID_PROGRAMS, AC=BROKER_EXPO, AD=BROKER_IMPO, AE=CLAVE_TRANSFER, AF=TRANSFORMA_SUBMAQ, AG=CLAVE_WEB,
AH=COL_EXTRA (desfase).
"""

from typing import Dict, List, Any, Optional

from ..common.cell_value import cell_to_str
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 .common.csv_max_chars_for_headers import CLIENT_PROVIDER_CSV_COLUMN_MAX_CHARS

TEMPLATE_COLUMNS: Dict[str, List[Dict[str, Any]]] = {
    "client_providers": [
        # Col A - Procedencia (E=Extranjero, N=Nacional). Manual: select N/E (≤3). Ver CSV_HEADER_HINTS.md
        {
            "canonical": "PROCEDENCIA",
            "aliases": ["TIPO PROCEDENCIA", "EXTranjero/Nacional", "E/N"],
            "csv_hint": {"kind": "enum_codes", "codes": ["N", "E"]},
        },
        # Col B - Tipo Cliente (C/P/A). Manual: client/provider/both (≤3). Ver CSV_HEADER_HINTS.md
        {
            "canonical": "TIPO",
            "aliases": ["CLIENT_OR_PROVIDER", "TIPO ENTIDAD", "CLIENTE O PROVEEDOR"],
            "csv_hint": {"kind": "enum_codes", "codes": ["C", "P", "A"]},
        },
        # Col C - Clave cliente/proveedor (máx 8 Clarion)
        {"canonical": "SHORT_NAME", "aliases": ["CLAVE", "CLAVE CORTA", "NOMBRE CORTO", "SIGLAS"]},
        # Col D - Nombre
        {"canonical": "NOMBRE", "aliases": ["RAZON SOCIAL", "NAME", "RAZON SOCIAL O NOMBRE"]},
        # Col E - RFC
        {"canonical": "RFC", "aliases": ["TAX_ID", "TAXID", "IDENTIFICADOR FISCAL", "IDENTIFICACION FISCAL"]},
        # Col F - Calles
        {"canonical": "DIRECCION", "aliases": ["CALLES", "DOMICILIO", "DIRECCION FISCAL", "CALLE"]},
        # Col G - Número exterior
        {"canonical": "NUM_EXT", "aliases": ["NUM EXTERIOR", "NUMERO EXTERIOR", "NO EXT"]},
        # Col H - Código postal
        {"canonical": "CODIGO POSTAL", "aliases": ["CODIGOPOSTAL", "CP", "C.P."]},
        # Col I - Colonia
        {"canonical": "COLONIA", "aliases": []},
        # Col J - Ciudad
        {"canonical": "CIUDAD", "aliases": ["MUNICIPIO"]},
        # Col K - Estado
        {"canonical": "ESTADO", "aliases": []},
        # Col L - País M3
        {"canonical": "PAIS", "aliases": ["COUNTRY", "PAIS M3"]},
        # Col M - Teléfono
        {"canonical": "TELEFONO", "aliases": ["PHONE", "TEL", "TELEFONO CONTACTO"]},
        # Col N - Fax
        {"canonical": "FAX", "aliases": ["NUMERO DE FAX", "FAX NUMBER"]},
        # Col O - Email
        {"canonical": "EMAIL", "aliases": ["CORREO", "E-MAIL", "CORREO ELECTRONICO"]},
        # Col P - CURP
        {"canonical": "CURP", "aliases": []},
        # Col Q - Tipo programa SECON
        {"canonical": "TIPO_PROGRAMA_SECON", "aliases": ["PROGRAMA", "TIPO PROGRAMA SECON", "TIPO PROGRAMA"]},
        # Col R - Número programa SECON
        {"canonical": "NUM_PROGRAMA_SECON", "aliases": ["NUM PROGRAMA SECON", "NUMERO PROGRAMA"]},
        # Col S - Fecha autorización SECON
        {"canonical": "FECHA_AUT_SECON", "aliases": ["FECHA AUT SECON", "FECHA AUTORIZACION SECON"]},
        # Col T - Es Prosec?
        {"canonical": "ES_PROSEC", "aliases": ["ES PROSEC", "PROSEC"]},
        # Col U - Número autorización PROSEC
        {"canonical": "NUM_AUT_PROSEC", "aliases": ["NUM AUT PROSEC", "NUMERO AUTORIZACION PROSEC"]},
        # Col V - Vinculación (0/1/2)
        {"canonical": "VINCULACION", "aliases": []},
        # Col W - Es Empresa Certificada?
        {"canonical": "ES_EMPRESA_CERTIFICADA", "aliases": ["ES EMPRESA CERTIFICADA", "EMPRESA CERTIFICADA"]},
        # Col X - Registro empresa certificada
        {"canonical": "REGISTRO_EMPRESA_CERT", "aliases": ["REGISTRO EMPRESA CERTIFICADA", "REGISTRO EMP CERT"]},
        # Col Y - Información extra
        {"canonical": "INFORMACION_EXTRA", "aliases": ["INFORMACION EXTRA", "INFO EXTRA"]},
        # Col Z - Contacto
        {"canonical": "CONTACTO", "aliases": ["CONTACT", "PERSONA CONTACTO"]},
        # Col AA - Manufacturer ID
        {"canonical": "MANUFACTURER_ID", "aliases": ["MANUFACTURERID", "MANUFACTURER ID"]},
        # Col AB - Tax ID (programas)
        {"canonical": "TAX_ID_PROGRAMS", "aliases": ["TAX ID", "TAXID PROGRAMS"]},
        # Col AC - Broker exportación
        {"canonical": "BROKER_EXPO", "aliases": ["BROKER EXPO", "BROKER EXPORTACION"]},
        # Col AD - Broker importación
        {"canonical": "BROKER_IMPO", "aliases": ["BROKER IMPO", "BROKER IMPORTACION"]},
        # Col AE - Clave transfer
        {"canonical": "CLAVE_TRANSFER", "aliases": ["CLAVE TRANSFER", "TRANSFER KEY"]},
        # Col AF - Transformador/SubMaquila/Ninguno (T/S/N)
        {"canonical": "TRANSFORMA_SUBMAQ", "aliases": ["TRANSFORMADOR SUBMAQUILA", "TRASFORMA SUBMAQ"]},
        # Col AG - Clave interface web
        {"canonical": "CLAVE_WEB", "aliases": ["CLAVE WEB", "CLAVE INTERFACE WEB", "WEB KEY"]},
        # Col AH - Desfase (si tiene valor → advertencia)
        {"canonical": "COL_EXTRA", "aliases": ["DESFASE", "COLUMNA EXTRA"]},
        # Legacy / otros
        {"canonical": "RESPONSABLE", "aliases": ["RESPONSABLE AREA"]},
        {"canonical": "POSICION", "aliases": ["CARGO", "PUESTO"]},
        {"canonical": "INCOTERM", "aliases": []},
        {"canonical": "ACTIVO", "aliases": ["IS_ACTIVE", "ACTIVE", "ESTADO ACTIVO"]},
    ],
}

inject_en_labels_into_template_columns(TEMPLATE_COLUMNS)


def _inject_max_char_hints_client_providers(columns: Optional[List[Dict[str, Any]]]) -> None:
    """Añade csv_hint max_chars desde CLIENT_PROVIDER_CSV_COLUMN_MAX_CHARS (paridad modelos/MAX_LEN)."""
    if not columns:
        return
    for item in columns:
        if not isinstance(item, dict):
            continue
        canon = item.get("canonical")
        if not canon:
            continue
        n = CLIENT_PROVIDER_CSV_COLUMN_MAX_CHARS.get(str(canon).strip())
        if n is None:
            continue
        mc: Dict[str, Any] = {"kind": "max_chars", "n": n}
        ch = item.get("csv_hint")
        if ch is None:
            item["csv_hint"] = mc
        elif isinstance(ch, dict):
            item["csv_hint"] = [ch, mc]
        elif isinstance(ch, list):
            item["csv_hint"] = [*ch, mc]


_inject_max_char_hints_client_providers(TEMPLATE_COLUMNS.get("client_providers"))


def build_normalized_lookup(normalize_header_fn) -> Dict[str, str]:
    """normalized_header -> canonical_name para plantilla client_providers."""
    cols = TEMPLATE_COLUMNS.get("client_providers")
    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]:
    """Fila CSV con solo columnas de la plantilla, en nombres canónicos."""
    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
