"""内置 Skill 实现

提供基础 Skill：
- /help: 显示可用 Skill
- /reload: 重载 Skill
- /status: 显示 Skill 状态
"""

import logging
from typing import Any, Dict

from .base import BaseSkill, SkillArgument, SkillContext, SkillResult, SkillType

logger = logging.getLogger("agent")


class HelpSkill(BaseSkill):
    """帮助 Skill - 显示可用 Skill 列表"""

    name = "help"
    description = "显示所有可用 Skill 的列表和使用方法"
    arguments = [
        SkillArgument(
            name="skill_name",
            description="可选，指定要查看详细帮助的 Skill 名称",
            type="string",
            required=False,
        )
    ]
    category = "system"
    skill_type = SkillType.FLEXIBLE

    def __init__(self, **data):
        super().__init__(**data)
        self._registry = None

    def set_registry(self, registry):
        """设置注册表引用（用于获取 Skill 列表）"""
        self._registry = registry

    async def execute(self, args: Dict[str, Any], context: SkillContext) -> SkillResult:
        """执行帮助"""
        skill_name = args.get("skill_name")

        if skill_name:
            # 显示特定 Skill 的帮助
            if self._registry:
                skill = self._registry.get_skill(skill_name)
                if skill:
                    help_text = f"## /{skill.name}\n\n{skill.description}\n\n"
                    help_text += f"**分类**: {skill.category}\n"
                    help_text += f"**类型**: {skill.skill_type.value}\n\n"

                    if skill.arguments:
                        help_text += "**参数**:\n"
                        for arg in skill.arguments:
                            required = "必填" if arg.required else "可选"
                            help_text += f"- `{arg.name}` ({arg.type}, {required}): {arg.description}\n"

                    return SkillResult(
                        success=True,
                        message=help_text,
                        data={"skill_name": skill_name}
                    )
                else:
                    return SkillResult(
                        success=False,
                        message=f"Skill '{skill_name}' 不存在",
                        error=f"Skill '{skill_name}' not found"
                    )
            else:
                return SkillResult(
                    success=False,
                    message="Skill 注册表未初始化",
                    error="Registry not initialized"
                )
        else:
            # 显示所有 Skill
            if self._registry:
                skills = self._registry.list_skills()

                help_text = "## 可用 Skill\n\n"
                help_text += "使用 `/skill_name` 调用 Skill，参数用空格分隔。\n\n"

                # 按分类组织
                categories = {}
                for skill in skills:
                    if skill.category not in categories:
                        categories[skill.category] = []
                    categories[skill.category].append(skill)

                for category, category_skills in categories.items():
                    help_text += f"### {category.capitalize()}\n"
                    for skill in category_skills:
                        help_text += f"- `/{skill.name}`: {skill.description}\n"
                    help_text += "\n"

                help_text += "### 示例\n"
                help_text += "```\n"
                help_text += "/help              # 显示所有 Skill\n"
                help_text += "/help help         # 显示 help Skill 的详细帮助\n"
                help_text += "/status            # 显示系统状态\n"
                help_text += "/reload            # 重载所有 Skill\n"
                help_text += "```\n"

                return SkillResult(
                    success=True,
                    message=help_text,
                    data={"count": len(skills)}
                )
            else:
                return SkillResult(
                    success=False,
                    message="Skill 注册表未初始化",
                    error="Registry not initialized"
                )


class ReloadSkill(BaseSkill):
    """重载 Skill - 重新加载所有 Skill"""

    name = "reload"
    description = "重新加载所有 Skill（包含内置和本地 Skill）"
    arguments = []
    category = "system"
    skill_type = SkillType.RIGID

    def __init__(self, **data):
        super().__init__(**data)
        self._registry = None

    def set_registry(self, registry):
        """设置注册表引用"""
        self._registry = registry

    async def execute(self, args: Dict[str, Any], context: SkillContext) -> SkillResult:
        """执行重载"""
        try:
            if self._registry:
                collection = self._registry.reload()
                count = len(collection)

                # 重新设置注册表引用
                if self._registry.list_skills():
                    for skill in self._registry.list_skills():
                        if hasattr(skill, 'set_registry'):
                            skill.set_registry(self._registry)

                return SkillResult(
                    success=True,
                    message=f"Skill 重载成功，共加载 {count} 个 Skill",
                    data={"count": count}
                )
            else:
                return SkillResult(
                    success=False,
                    message="Skill 注册表未初始化",
                    error="Registry not initialized"
                )
        except Exception as e:
            logger.error(f"[ReloadSkill] 重载失败: {e}", exc_info=True)
            return SkillResult(
                success=False,
                message=f"Skill 重载失败: {str(e)}",
                error=str(e)
            )


class StatusSkill(BaseSkill):
    """状态 Skill - 显示 Skill 系统状态"""

    name = "status"
    description = "显示 Skill 系统的当前状态"
    arguments = []
    category = "system"
    skill_type = SkillType.FLEXIBLE

    def __init__(self, **data):
        super().__init__(**data)
        self._registry = None

    def set_registry(self, registry):
        """设置注册表引用"""
        self._registry = registry

    async def execute(self, args: Dict[str, Any], context: SkillContext) -> SkillResult:
        """执行状态查询"""
        try:
            if self._registry:
                skills = self._registry.list_skills(include_disabled=True)
                enabled_count = len(self._registry.list_skills())

                # 按来源统计
                from .loader import get_skill_loader
                loader = get_skill_loader()
                packages = loader.packages

                source_stats = {}
                for pkg in packages.values():
                    source_stats[pkg.source] = source_stats.get(pkg.source, 0) + 1

                status_text = "## Skill 系统状态\n\n"
                status_text += f"**总 Skill 数**: {len(skills)}\n"
                status_text += f"**已启用**: {enabled_count}\n"
                status_text += f"**已禁用**: {len(skills) - enabled_count}\n\n"

                status_text += "### 来源统计\n"
                for source, count in source_stats.items():
                    status_text += f"- {source}: {count}\n"

                status_text += "\n### 分类统计\n"
                categories = {}
                for skill in skills:
                    categories[skill.category] = categories.get(skill.category, 0) + 1
                for category, count in categories.items():
                    status_text += f"- {category}: {count}\n"

                return SkillResult(
                    success=True,
                    message=status_text,
                    data={
                        "total": len(skills),
                        "enabled": enabled_count,
                        "disabled": len(skills) - enabled_count,
                        "sources": source_stats,
                        "categories": categories,
                    }
                )
            else:
                return SkillResult(
                    success=False,
                    message="Skill 注册表未初始化",
                    error="Registry not initialized"
                )
        except Exception as e:
            logger.error(f"[StatusSkill] 获取状态失败: {e}", exc_info=True)
            return SkillResult(
                success=False,
                message=f"获取状态失败: {str(e)}",
                error=str(e)
            )
