"""TUI / Host 共用的轻量偏好（如主对话 ``/mode``），持久化在 ``HOME/data/tui_prefs.json``。"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Final

MAIN_CHAT_CANONICAL_MODES: Final[frozenset[str]] = frozenset({"default", "chat", "doc"})
TUI_PREFS_FILENAME = "tui_prefs.json"


def parse_main_chat_mode_token(raw: str) -> tuple[str | None, str]:
    """
    解析 ``/mode``、Host 参数中的模式名。

    返回 ``(canonical, err)``：成功时 ``canonical`` 为 ``default|chat|doc`` 且 ``err==""``；
    ``err=="help"`` 表示帮助意图；否则 ``canonical is None`` 且 ``err`` 为可读错误。
    """
    m = (raw or "").strip().lower()
    if not m:
        return None, "empty"
    if m in ("help", "?", "h"):
        return None, "help"
    if m in ("default", "balanced", "normal", "standard"):
        return "default", ""
    if m in ("chat", "qa", "q&a", "ask"):
        return "chat", ""
    if m in ("doc", "deliver", "author", "files", "library"):
        return "doc", ""
    return None, f"未知模式 {raw!r}；可用 default、chat、doc"


def load_main_chat_mode(data_dir: Path) -> str | None:
    """从 ``data_dir/tui_prefs.json`` 读取 ``main_chat_mode``；非法或缺失返回 ``None``。"""
    p = (data_dir / TUI_PREFS_FILENAME).resolve()
    if not p.is_file():
        return None
    try:
        obj = json.loads(p.read_text(encoding="utf-8"))
        if not isinstance(obj, dict):
            return None
        m = str(obj.get("main_chat_mode", "")).strip().lower()
        if m in MAIN_CHAT_CANONICAL_MODES:
            return m
    except (OSError, json.JSONDecodeError, TypeError):
        pass
    return None


def save_main_chat_mode(data_dir: Path, mode: str) -> None:
    """合并写入 ``main_chat_mode``；保留 JSON 内其它键。"""
    if mode not in MAIN_CHAT_CANONICAL_MODES:
        return
    data_dir = data_dir.resolve()
    data_dir.mkdir(parents=True, exist_ok=True)
    p = data_dir / TUI_PREFS_FILENAME
    prev: dict[str, object] = {}
    if p.is_file():
        try:
            loaded = json.loads(p.read_text(encoding="utf-8"))
            if isinstance(loaded, dict):
                prev = dict(loaded)
        except (OSError, json.JSONDecodeError, TypeError):
            prev = {}
    prev["main_chat_mode"] = mode
    p.write_text(
        json.dumps(prev, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
