"""Test agent engine — build_agent, skill registry loader."""

from __future__ import annotations

from pathlib import Path
from unittest.mock import MagicMock, patch
from uuid import uuid4

import pytest
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.base import empty_checkpoint

from app.core.agent_engine import (
    _build_skill_recommendation_prompt,
    _load_skills_registry,
    build_agent,
)
from app.core.memory import get_memory_saver, get_thread_messages


class TestLoadSkillsRegistry:
    def test_skills_dir_not_found(self):
        reg = _load_skills_registry()
        assert isinstance(reg, dict)

    def test_empty_skips_non_skill_md(self, tmp_path):
        skills_dir = tmp_path / "skills"
        skills_dir.mkdir()
        sk = skills_dir / "readme.md"
        sk.write_text("not a SKILL.md", encoding="utf-8")
        with patch("app.core.agent_engine.Path", wraps=Path) as mock_path:
            mock_path_instance = MagicMock()
            mock_path_instance.resolve.return_value.parents = [None, None, None, tmp_path]
            # The actual implementation uses parents[3], so we'd need a 4-element parents
            # Instead, just test the function with the real Path but override skills_dir existence

    def test_skill_with_valid_frontmatter(self, tmp_path):
        skills_dir = tmp_path / "skills"
        skills_dir.mkdir()
        skill_md = skills_dir / "verify-agent" / "SKILL.md"
        skill_md.parent.mkdir()
        skill_md.write_text(
            "---\nname: verify-agent\ndescription: 验证模型适配\n---\n\n# Content\n",
            encoding="utf-8",
        )
        with patch.object(Path, "is_dir", return_value=True):
            with patch.object(Path, "rglob") as mock_rglob:
                mock_rglob.return_value = [skill_md]
                reg = _load_skills_registry()
                assert "verify-agent" in reg
                assert "验证模型适配" in reg["verify-agent"]


class TestBuildSkillRecommendationPrompt:
    def test_empty_registry_returns_empty(self):
        with patch("app.core.agent_engine._load_skills_registry", return_value={}):
            result = _build_skill_recommendation_prompt()
            assert result == ""

    def test_with_registry_returns_prompt(self):
        with patch("app.core.agent_engine._load_skills_registry", return_value={
            "verify-agent": "验证模型适配",
            "optimizer-agent": "vLLM 性能调优",
        }):
            result = _build_skill_recommendation_prompt()
            assert "verify-agent" in result
            assert "optimizer-agent" in result
            assert "验证模型适配" in result
            assert "/claude" in result
            assert "→ 推荐回复格式:`/claude verify-agent [具体任务描述]`" in result
            assert "若匹配,**直接回复一条以 `/claude` 开头的可复制提示词**" in result
            assert "若用户提到具体 Skill 名称,直接给出对应 /claude 命令" in result
            assert "若需求明显属于验证/适配/优化/量化/迁移等范畴" in result
            assert "仅询问 Skill 来源时先调用 list_claude_skills 核实" in result
            assert "明确要求执行时调用已绑定的对应工具" in result
            assert "其他情况沿用上述 `/claude` 推荐格式" in result


class TestBuildAgent:
    def test_agent_and_skill_context_share_the_same_memory(self):
        with (
            patch("app.core.agent_engine.build_llm"),
            patch("app.core.agent_engine.get_chat_tools", return_value=[]),
            patch("app.core.agent_engine.create_react_agent") as create_agent,
        ):
            build_agent(streaming=False)

        saver = create_agent.call_args.kwargs["checkpointer"]
        assert saver is get_memory_saver()

        thread_id = f"memory-bridge-{uuid4().hex}"
        checkpoint = empty_checkpoint()
        checkpoint["channel_values"]["messages"] = [HumanMessage(content="历史问题")]
        checkpoint["channel_versions"]["messages"] = "1"
        try:
            saver.put(
                {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}},
                checkpoint, {}, {"messages": "1"},
            )
            assert [message.content for message in get_thread_messages(thread_id)] == ["历史问题"]
        finally:
            saver.delete_thread(thread_id)

    def test_build_agent_basic(self):
        with patch("app.core.agent_engine.build_llm") as mock_build_llm:
            with patch("app.core.agent_engine.get_chat_tools", return_value=[]):
                mock_agent = MagicMock()
                with patch("app.core.agent_engine.create_react_agent", return_value=mock_agent):
                    agent = build_agent(streaming=False)
                    assert agent is mock_agent

    def test_build_agent_with_cmd_registry(self):
        with patch("app.core.agent_engine.build_llm"):
            with patch("app.core.agent_engine.get_chat_tools", return_value=[]):
                mock_registry = MagicMock()
                mock_registry.build_system_prompt_addon.return_value = "\n## Commands"
                mock_agent = MagicMock()
                with patch("app.core.agent_engine.create_react_agent", return_value=mock_agent):
                    agent = build_agent(streaming=False, cmd_registry=mock_registry)
                    assert agent is mock_agent

    def test_build_agent_with_user_system_prompt(self):
        with patch("app.core.agent_engine.build_llm"):
            with patch("app.core.agent_engine.get_chat_tools", return_value=[]):
                mock_agent = MagicMock()
                with patch("app.core.agent_engine.create_react_agent", return_value=mock_agent):
                    agent = build_agent(streaming=True, user_system_prompt="Custom prompt")
                    assert agent is mock_agent

    def test_build_agent_filters_explicitly_blocked_tools(self):
        allowed = MagicMock()
        allowed.name = "read_only"
        blocked = MagicMock()
        blocked.name = "quantify_run_msmodelslim"
        with (
            patch("app.core.agent_engine.build_llm"),
            patch(
                "app.core.agent_engine.get_chat_tools",
                return_value=[allowed, blocked],
            ),
            patch("app.core.agent_engine.create_react_agent", return_value=MagicMock()),
            patch("app.core.agent_engine.ToolNode") as tool_node,
        ):
            build_agent(
                blocked_tool_names={"quantify_run_msmodelslim"},
            )
        assert tool_node.call_args.args[0] == [allowed]


class TestToolErrorFeedback:
    """FileExistsError/ValueError 经 ToolNode handle_tool_errors 回喂;行为级验证依赖真实图执行,此处只钉接线。"""

    def test_build_agent_wraps_tools_in_tool_node(self):
        with patch("app.core.agent_engine.build_llm"):
            with patch("app.core.agent_engine.get_chat_tools", return_value=[]):
                mock_agent = MagicMock()
                with patch("app.core.agent_engine.create_react_agent", return_value=mock_agent) as cra:
                    with patch("app.core.agent_engine.ToolNode") as mock_tool_node:
                        agent = build_agent(streaming=False)
                        assert agent is mock_agent
                        args, _ = cra.call_args
                        assert args[1] is mock_tool_node.return_value
                        tn_args, tn_kwargs = mock_tool_node.call_args
                        assert tn_args[0] == []
                        assert callable(tn_kwargs.get("handle_tool_errors"))