"""build_skill_system_prompt preconditions 注入单元测试"""

from types import SimpleNamespace

from agentkit.chat.skill_routing import build_skill_system_prompt


def _make_config(prompt=None, preconditions=None):
    """构造一个轻量 skill_config 替身（避免 SkillConfig 的校验开销）"""
    return SimpleNamespace(prompt=prompt, preconditions=preconditions)


class TestBuildSkillSystemPromptPreconditions:
    def test_with_preconditions_appends_block(self):
        cfg = _make_config(
            prompt={"identity": "You are a reviewer.", "instructions": "Review code."},
            preconditions=["需要代码仓库访问权限", "当前分支非 main"],
        )
        out = build_skill_system_prompt(cfg)
        assert out is not None
        assert "## Activation Preconditions" in out
        assert "需要代码仓库访问权限" in out
        assert "当前分支非 main" in out
        # 基础段落仍在
        assert "You are a reviewer." in out
        assert "Review code." in out
        # preconditions 段落在基础段落之后
        assert out.index("You are a reviewer.") < out.index("## Activation Preconditions")

    def test_none_preconditions_unchanged(self):
        """preconditions 为 None 时输出与无 preconditions 完全一致"""
        cfg_no_pre = _make_config(prompt={"identity": "X"})
        cfg_none = _make_config(prompt={"identity": "X"}, preconditions=None)
        assert build_skill_system_prompt(cfg_no_pre) == build_skill_system_prompt(cfg_none)

    def test_empty_list_preconditions_no_block(self):
        cfg = _make_config(prompt={"identity": "X"}, preconditions=[])
        out = build_skill_system_prompt(cfg)
        assert out is not None
        assert "## Activation Preconditions" not in out

    def test_no_prompt_returns_none(self):
        cfg = _make_config(prompt=None, preconditions=["条件A"])
        assert build_skill_system_prompt(cfg) is None

    def test_empty_prompt_and_preconditions_returns_none(self):
        """prompt 为空字典时返回 None（现有行为），即使有 preconditions 也不注入"""
        cfg = _make_config(prompt={}, preconditions=["条件A"])
        # 现有逻辑：prompt_parts 为空 → base 为 None；preconditions 非空但无 base
        # 按 KTD1，preconditions 是"激活后行为约束"，无基础 prompt 时不单独输出
        out = build_skill_system_prompt(cfg)
        # base 为 None 时，preconditions_block 仍会返回（f"{base}\n\n{block}" if base else block）
        # 但 prompt={} 时 not skill_config.prompt 为 False（空 dict 是 falsy? 不，{} is falsy）
        # 实际：if not skill_config.prompt → {} is falsy → return None
        assert out is None
