"""
Configuración de plantilla CSV para Fracción Americana (EstructuraCatFraccAme.xls).
Solo se leen columnas definidas aquí; el resto se ignora.
"""

from typing import Dict, List, Any, Optional

from ..common.cell_value import cell_to_str as _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 US_TARIFF_FRACTIONS_CSV_MAX_CHARS

TEMPLATE_COLUMNS: Dict[str, List[Dict[str, Any]]] = {
    "us_tariff_fractions": [
        {"canonical": "FRACCION_ARANCELARIA", "aliases": ["FRACCION ARANCELARIA", "CODE", "FRACCION"]},
        {"canonical": "PREFIJO"},
        {"canonical": "UNIDAD_DE_MEDIDA", "aliases": ["UNIDAD DE MEDIDA", "UMT"]},
        {"canonical": "DESCRIPCION"},
        {"canonical": "TIPO_DE_ADVALOREM", "aliases": ["TIPO DE ADVALOREM", "TIPO"]},
        {"canonical": "ADVALOREM_PCT", "aliases": ["ADVALOREM %", "ADVALOREM"]},
        {"canonical": "ADVALOREM_DLLS", "aliases": ["ADVALOREM DLLS", "ADVALOREM DLL"]},
        {"canonical": "COL_EXTRA", "aliases": ["DESFASE"]},
    ],
}

inject_en_labels_into_template_columns(TEMPLATE_COLUMNS)

inject_max_char_hints_into_columns(
    TEMPLATE_COLUMNS.get("us_tariff_fractions"), US_TARIFF_FRACTIONS_CSV_MAX_CHARS
)
for _uc in TEMPLATE_COLUMNS.get("us_tariff_fractions") or []:
    if _uc.get("canonical") == "TIPO_DE_ADVALOREM":
        merge_enum_hint_before_max(_uc, ["PO", "ME"])

# Orden A..H para detectar desfase en 8ª columna (raw_row.values()[7])
TEMPLATE_ORDER = [item["canonical"] for item in TEMPLATE_COLUMNS["us_tariff_fractions"]]
DESFASE_COLUMN_INDEX = 7


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