"""MCP Skill Builder - Phase 9.3"""

from typing import Any

from app.agents.skills.metadata import SkillMetadata


class MCPSkillBuilder:
    """MCP Skill Builder

    从 MCP 服务器发现和构建 Skills。
    """

    def __init__(self):
        self._skills: dict[str, SkillMetadata] = {}

    def discover_skills_from_mcp(self, mcp_servers: list[dict[str, Any]]) -> list[SkillMetadata]:
        """从 MCP 服务器发现 Skills

        Args:
            mcp_servers: MCP 服务器配置列表

        Returns:
            发现的 Skill 元数据列表
        """
        skills = []

        for server in mcp_servers:
            server_skills = self._discover_from_server(server)
            skills.extend(server_skills)

        return skills

    def _discover_from_server(self, server: dict[str, Any]) -> list[SkillMetadata]:
        """从单个 MCP 服务器发现 Skills"""
        skills = []
        server_name = server.get("name", "unknown")
        tools = server.get("tools", [])

        # 按工具分组
        tool_groups: dict[str, list[str]] = {}
        for tool in tools:
            group = tool.get("group", "default")
            if group not in tool_groups:
                tool_groups[group] = []
            tool_groups[group].append(tool)

        # 为每个组创建一个 Skill
        for group_name, group_tools in tool_groups.items():
            skill = self._tool_to_skill(group_name, group_tools, server_name)
            skills.append(skill)

        return skills

    def _tool_to_skill(self, group: str, tools: list[dict[str, Any]], server: str) -> SkillMetadata:
        """将 MCP 工具转换为 Skill"""
        tool_summaries = []
        for tool in tools:
            name = tool.get("name", "unknown")
            description = tool.get("description", "")
            input_schema = tool.get("inputSchema", {})

            tool_summaries.append(f"### {name}\n{description}\n\nInput: {input_schema}")

        content = f"""# MCP Skill: {group}

来自 MCP 服务器: {server}

## 工具列表

{chr(10).join(tool_summaries)}

## 使用说明

使用这些工具前请确保理解每个工具的输入输出格式。
"""

        return SkillMetadata(
            name=f"mcp-{server}-{group}",
            description=f"MCP skill from {server}: {group}",
            version="1.0.0",
            tags=["mcp", server, group],
            triggers=[group, server],
            content=content,
            source="mcp",
            source_id=f"{server}:{group}",
        )

    def _group_to_skill(self, group: str, tools: list[str], server: str) -> SkillMetadata:
        """将 MCP 工具组转换为 Skill"""
        return SkillMetadata(
            name=f"mcp-{server}-{group}",
            description=f"MCP skill from {server}: {group}",
            version="1.0.0",
            tags=["mcp", server, group],
            triggers=[group, server],
            content=f"# {group}\n\nTools: {', '.join(tools)}",
            source="mcp",
            source_id=f"{server}:{group}",
        )
