"""TOML-based configuration management for video-thumbnail-creator."""

import copy
import os
from pathlib import Path

try:
    import tomllib  # Python 3.11+
except ImportError:
    try:
        import tomli as tomllib  # type: ignore[no-redef]
    except ImportError:
        tomllib = None  # type: ignore[assignment]

try:
    import tomli_w
except ImportError:
    tomli_w = None  # type: ignore[assignment]

CONFIG_DIR = Path.home() / ".config" / "video-thumbnail-creator"
CONFIG_FILE = CONFIG_DIR / "config.toml"

# All recognised section.key pairs
ALLOWED_KEYS = frozenset(
    {
        "claude.api_key",
        "claude.model",
        "tools.ffmpeg",
        "tools.ffprobe",
        "defaults.output_name_suffix",
        "defaults.mode",
        "defaults.format",
        "defaults.embedded_image",
        "badges.enabled",
    }
)

# Built-in defaults
_BUILTIN_DEFAULTS: dict = {
    "claude": {
        "model": "claude-opus-4-5",
    },
    "tools": {
        "ffmpeg": "ffmpeg",
        "ffprobe": "ffprobe",
    },
    "defaults": {
        "output_name_suffix": "-poster",
        "mode": "manual",
        "format": "poster",
        "embedded_image": "ask",
    },
}


def load_config() -> dict:
    """Load config from ``~/.config/video-thumbnail-creator/config.toml``.

    Returns an empty dict when the file does not exist or cannot be parsed.
    """
    if not CONFIG_FILE.exists():
        return {}
    if tomllib is None:
        return {}
    with open(CONFIG_FILE, "rb") as fh:
        return tomllib.load(fh)


def save_config(config: dict) -> None:
    """Write *config* to ``config.toml``, creating the directory if needed."""
    if tomli_w is None:
        raise RuntimeError(
            "The 'tomli-w' package is required to write configuration. "
            "Install it with: pip install tomli-w"
        )
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    with open(CONFIG_FILE, "wb") as fh:
        tomli_w.dump(config, fh)


def _validate_key(key: str) -> None:
    if key not in ALLOWED_KEYS:
        allowed = ", ".join(sorted(ALLOWED_KEYS))
        raise ValueError(
            f"Unknown config key '{key}'. Allowed keys: {allowed}"
        )


def get_value(key: str) -> str | None:
    """Return the stored value for *key* (``section.field``), or ``None``."""
    _validate_key(key)
    section, field = key.split(".", 1)
    return load_config().get(section, {}).get(field)


def set_value(key: str, value: str) -> None:
    """Persist *value* for *key* without touching other keys."""
    _validate_key(key)
    section, field = key.split(".", 1)
    config = load_config()
    config.setdefault(section, {})[field] = value
    save_config(config)


def list_config() -> dict:
    """Return the currently stored config (file values only, no defaults)."""
    return load_config()


def get_effective_config() -> dict:
    """Return built-in defaults merged with file values (file takes priority)."""
    result = copy.deepcopy(_BUILTIN_DEFAULTS)
    for section, values in load_config().items():
        result.setdefault(section, {}).update(values)
    return result
