"""Helpers to merge csv_hint max_chars into column definitions after inject_en_labels."""
from __future__ import annotations

from typing import Any, Dict, List, Optional


def inject_max_char_hints_into_columns(
    columns: Optional[List[Dict[str, Any]]],
    max_by_canonical: Dict[str, int],
) -> None:
    """Attach or append ``{\"kind\": \"max_chars\", \"n\": N}`` per canonical (aligned with validators/models)."""
    if not columns or not max_by_canonical:
        return
    for item in columns:
        if not isinstance(item, dict):
            continue
        canon = item.get("canonical")
        if not canon:
            continue
        n = max_by_canonical.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]


def append_csv_hint(item: Dict[str, Any], extra: Dict[str, Any]) -> None:
    """Añade un hint (digits, enum adicional, etc.) tras los existentes."""
    ch = item.get("csv_hint")
    if ch is None:
        item["csv_hint"] = extra
        return
    if isinstance(ch, dict):
        item["csv_hint"] = [ch, extra]
        return
    if isinstance(ch, list):
        item["csv_hint"] = [*ch, extra]


def merge_enum_hint_before_max(
    item: Dict[str, Any],
    enum_codes: List[str],
) -> None:
    """Prepend enum_codes hint if not already present (for columns with fixed ≤3 values)."""
    if len(enum_codes) == 0 or len(enum_codes) > 3:
        return
    enum_hint: Dict[str, Any] = {"kind": "enum_codes", "codes": list(enum_codes)}
    ch = item.get("csv_hint")
    if ch is None:
        item["csv_hint"] = enum_hint
        return
    if isinstance(ch, dict):
        if ch.get("kind") == "enum_codes":
            return
        item["csv_hint"] = [enum_hint, ch]
        return
    if isinstance(ch, list):
        if any(isinstance(x, dict) and x.get("kind") == "enum_codes" for x in ch):
            return
        item["csv_hint"] = [enum_hint, *ch]
