"""主对话 /mode：系统提示后缀、tui_prefs 解析与持久化。"""

from __future__ import annotations

import json
from pathlib import Path

from aicd.agent.prompts import MAIN_CHAT_MODE_CHAT_SUFFIX, MAIN_CHAT_MODE_DOC_SUFFIX
from aicd.tui_prefs import (
    MAIN_CHAT_CANONICAL_MODES,
    load_main_chat_mode,
    parse_main_chat_mode_token,
    save_main_chat_mode,
)


def test_chat_mode_suffix_documents_tui_toggle() -> None:
    low = MAIN_CHAT_MODE_CHAT_SUFFIX.lower()
    assert "chat-first" in low
    assert "/mode default" in MAIN_CHAT_MODE_CHAT_SUFFIX or "/mode doc" in MAIN_CHAT_MODE_CHAT_SUFFIX


def test_doc_mode_suffix() -> None:
    assert "doc-first" in MAIN_CHAT_MODE_DOC_SUFFIX.lower()
    assert "deliverables" in MAIN_CHAT_MODE_DOC_SUFFIX.lower()


def test_parse_main_chat_mode_token() -> None:
    assert parse_main_chat_mode_token("chat") == ("chat", "")
    assert parse_main_chat_mode_token("DOC") == ("doc", "")
    assert parse_main_chat_mode_token("library")[0] == "doc"
    _, err = parse_main_chat_mode_token("help")
    assert err == "help"
    assert parse_main_chat_mode_token("nope")[0] is None


def test_tui_prefs_roundtrip(tmp_path: Path) -> None:
    d = tmp_path / "data"
    d.mkdir()
    save_main_chat_mode(d, "chat")
    assert load_main_chat_mode(d) == "chat"
    raw = json.loads((d / "tui_prefs.json").read_text(encoding="utf-8"))
    assert raw.get("other") is None
    save_main_chat_mode(d, "doc")
    raw = json.loads((d / "tui_prefs.json").read_text(encoding="utf-8"))
    assert raw["main_chat_mode"] == "doc"
    assert load_main_chat_mode(d) == "doc"


def test_canonical_modes_cover_three() -> None:
    assert len(MAIN_CHAT_CANONICAL_MODES) == 3
    for x in ("default", "chat", "doc"):
        assert x in MAIN_CHAT_CANONICAL_MODES
