"""Configuration du client STT.

Défauts embarqués (robuste pour pipx). `stt --setup` les écrit dans
~/.config/stt/stt.toml ; au lancement on fusionne le fichier utilisateur par-dessus.

Le client ne contient PLUS le cerveau : il envoie le texte au STT-server (URL paramétrable).
"""

from __future__ import annotations

import tomllib
from pathlib import Path
from typing import Any

CONFIG_DIR = Path.home() / ".config" / "stt"
CONFIG_PATH = CONFIG_DIR / "stt.toml"
DATA_DIR = Path.home() / ".local" / "share" / "stt"

# Noms courts → alias LiteLLM (pour --model et la commande /model)
MODEL_PRESETS = {
    "hermes": "hermes-default",   # Qwen3-8B local (défaut, gratuit)
    "qwen": "qwen3-8b",
    "claude": "claude-sonnet-4-6",  # Claude (facturé)
    "opus": "claude-opus-4-7",
}


def resolve_model(name: str) -> str:
    """Nom court → alias LiteLLM (ou renvoie tel quel si déjà un alias)."""
    return MODEL_PRESETS.get(name, name)

DEFAULT_CONFIG: dict[str, Any] = {
    "server": {
        # STT-server (in-cluster) — joignable via Traefik / wildcard *.lab.local
        "url": "http://stt.lab.local",
        "timeout_sec": 90,
        # Modèle demandé au serveur (alias LiteLLM, ou nom court ci-dessous)
        "model": "hermes-default",
    },
    "voice": {
        "wake_word": "hermes",
        "whisper_model": "large-v3",
        "piper_voice": "fr_FR-upmc-medium",
        "language": "fr",
        "silence_sec": 1.2,
        "min_speech_sec": 0.6,
        "chat_timeout_sec": 60,
    },
    "ui": {
        "theme": "arc-reactor",
        "avatar": "default",
        "kiosk": True,
        "ws_host": "127.0.0.1",
        "ws_port": 9300,
        "http_port": 9301,
    },
    "memory": {
        # cache local de conversation (brut, gitignoré) — la vraie mémoire est côté serveur
        "enabled": True,
        "local_db": str(DATA_DIR / "memory.sqlite"),
    },
}


def _deep_merge(base: dict, over: dict) -> dict:
    out = dict(base)
    for k, v in over.items():
        if isinstance(v, dict) and isinstance(out.get(k), dict):
            out[k] = _deep_merge(out[k], v)
        else:
            out[k] = v
    return out


def load_config() -> dict[str, Any]:
    if CONFIG_PATH.exists():
        with CONFIG_PATH.open("rb") as f:
            user = tomllib.load(f)
        return _deep_merge(DEFAULT_CONFIG, user)
    return DEFAULT_CONFIG


def write_default_config(force: bool = False) -> Path:
    import tomli_w

    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    if CONFIG_PATH.exists() and not force:
        return CONFIG_PATH
    with CONFIG_PATH.open("wb") as f:
        tomli_w.dump(DEFAULT_CONFIG, f)
    return CONFIG_PATH
