"""小鉴 LLM regime 推断 — heavy 档 left 模块 JSON。"""

from __future__ import annotations

import json
from typing import Any

from niannian.cognitive.planes import Regime
from niannian.llm.router import LLMRouter
from niannian.llm.types import LLMUnavailable, Message
from niannian.personas import JUDGMENT

_REGIMES: frozenset[str] = frozenset({"companion", "work", "hybrid", "education"})


def detect_regime_llm(
    combined: str,
    *,
    config: dict[str, Any],
    llm: LLMRouter,
) -> tuple[Regime, float] | None:
    """left LLM 推断 regime；失败或低 confidence 返回 None。"""
    if not llm.is_module_configured("left"):
        return None

    chat_cfg = config.get("chat") or {}
    threshold = float(chat_cfg.get("regime_confidence_threshold", 0.7))
    stripped = combined.strip()
    if not stripped:
        return None

    system = (
        "你是小鉴，判断用户当前对话应处于哪种 regime。"
        "companion=陪伴闲聊 · work=技术/工作/代码 · hybrid=工作+情感交织 · education=讲解/学习。"
        "输出 JSON：{\"regime\":\"companion|work|hybrid|education\",\"confidence\":0.0~1.0}"
    )
    user_msg = f"最近用户消息（新→旧）：\n{stripped}"

    try:
        result = llm.complete(
            "left",
            [
                Message(role="system", content=system),
                Message(role="user", content=user_msg),
            ],
            json_mode=True,
            temperature=0.2,
        )
        parsed = json.loads(result.text)
    except (LLMUnavailable, json.JSONDecodeError, TypeError, KeyError):
        return None

    regime_raw = parsed.get("regime")
    if regime_raw not in _REGIMES:
        return None
    try:
        confidence = float(parsed.get("confidence", 0))
    except (TypeError, ValueError):
        return None
    if confidence < threshold:
        return None
    return regime_raw, confidence  # type: ignore[return-value]


def trace_regime_source(regime: Regime, source: str) -> str:
    return f"[{JUDGMENT}] regime={regime} ({source})"
