from pydantic import BaseModel, Field
from .base import BaseTool
from core.skill import get_skill_manager
from core.logger import log_event


class SkillArgs(BaseModel):
    """Arguments for Skill tool"""

    skill: str = Field(..., description="The skill name (no arguments)")


class SkillTool(BaseTool):
    """Tool for invoking skills"""

    name = "skill"
    args_schema = SkillArgs

    def __init__(self):
        self.manager = get_skill_manager()

    @property
    def description(self) -> str:
        """动态生成 description，包含可用 skill 列表"""
        skills = self.manager.get_all_skills()

        base = """Execute a skill within the main conversation.

Skills provide specialized capabilities and domain knowledge. When users ask you to perform tasks, check if any available skills match the task and invoke them.

How to use skills:
- Invoke skills using this tool with the skill name only (no arguments)
- When you invoke a skill, the skill's prompt will expand and provide detailed instructions
- Only use skills listed in available skills below
- Do not invoke a skill that is already running"""

        if skills:
            skill_list = "\n\nAvailable skills:\n"
            for s in skills:
                skill_list += f"- **{s.name}**: {s.description}\n"
            return base + skill_list
        else:
            return base + "\n\nNo skills currently available."

    async def run(self, skill: str) -> str:
        """Execute the tool"""
        try:
            # Load skill content
            content = self.manager.load_skill_content(skill)

            if not content:
                available_skills = [s.name for s in self.manager.get_all_skills()]
                error_msg = f"Skill '{skill}' not found. Available skills: {', '.join(available_skills)}"

                log_event(
                    "skill_execution",
                    skill_name=skill,
                    skill_path="",
                    result="",
                    error=error_msg
                )

                return error_msg

            # 记录成功的 skill 执行
            skill_info = self.manager.get_skill(skill)
            skill_path = str(skill_info.location) if skill_info else ""

            log_event(
                "skill_execution",
                skill_name=skill,
                skill_path=skill_path,
                result=content,
                error=None
            )

            # Return skill content to be injected into the conversation
            return f"Skill '{skill}' loaded:\n\n{content}"

        except Exception as e:
            error_msg = f"Error loading skill '{skill}': {str(e)}"

            log_event(
                "skill_execution",
                skill_name=skill,
                skill_path="",
                result="",
                error=error_msg
            )

            return error_msg
