"""Chat mode → Skill name bindings (skills.mode_packs in config)."""

from __future__ import annotations

from typing import Any

from niannian.core.config import load_config

_MODE_PACK_KEYS = frozenset({"companion", "work", "study", "auto"})

_CHAT_MODE_ALIASES: dict[str, str] = {
    "education": "study",
    "default": "auto",
}


def _pack_key(chat_mode: str | None) -> str:
    key = str(chat_mode or "auto").strip().lower()
    key = _CHAT_MODE_ALIASES.get(key, key)
    if key not in _MODE_PACK_KEYS:
        return "auto"
    return key


def _mode_packs(config: dict[str, Any] | None = None) -> dict[str, list[str]]:
    cfg = config if config is not None else load_config()
    raw = (cfg.get("skills") or {}).get("mode_packs") or {}
    if not isinstance(raw, dict):
        return {key: [] for key in _MODE_PACK_KEYS}
    out: dict[str, list[str]] = {key: [] for key in _MODE_PACK_KEYS}
    for key in _MODE_PACK_KEYS:
        names = raw.get(key)
        if isinstance(names, list):
            out[key] = [str(name).strip() for name in names if str(name).strip()]
    return out


def resolve_mode_skill_names(chat_mode: str | None, *, config: dict[str, Any] | None = None) -> list[str]:
    """Return skill names bound to *chat_mode* via ``skills.mode_packs``."""
    packs = _mode_packs(config)
    return list(packs.get(_pack_key(chat_mode)) or [])
