import inspect
from typing import Any

from pydantic_ai_skills import SkillResourceNotFoundError, SkillsToolset

_original_call_tool = SkillsToolset.call_tool


async def _patched_call_tool(
    self: SkillsToolset, name: str, tool_args: dict[str, Any], ctx: Any, tool: Any
) -> Any:
    try:
        return await _original_call_tool(self, name, tool_args, ctx, tool)
    except SkillResourceNotFoundError as e:
        return (
            f"{e}\n\n"
            "IMPORTANT: Use load_skill first to read the skill's instructions and discover "
            "the correct script names and parameters before calling run_skill_script."
        )


SkillsToolset.call_tool = _patched_call_tool  # type: ignore[method-assign]

if "auto_reload" not in inspect.signature(SkillsToolset.__init__).parameters:
    _original_init = SkillsToolset.__init__
    _original_get_instructions = SkillsToolset.get_instructions

    def _patched_init(
        self: SkillsToolset, *args: Any, auto_reload: bool = False, **kwargs: Any
    ) -> None:
        _original_init(self, *args, **kwargs)
        self._auto_reload = auto_reload  # type: ignore[attr-defined]

    def _reload(self: SkillsToolset) -> None:
        new_skills: dict[str, Any] = {}
        for skill_dir in self._skill_directories:
            for skill in skill_dir.get_skills().values():
                if skill.name not in new_skills:
                    new_skills[skill.name] = skill
        self._skills = new_skills

    async def _patched_get_instructions(
        self: SkillsToolset, *args: Any, **kwargs: Any
    ) -> str | None:
        if getattr(self, "_auto_reload", False):
            _reload(self)
        return await _original_get_instructions(self, *args, **kwargs)

    SkillsToolset.__init__ = _patched_init  # type: ignore[method-assign]
    SkillsToolset.reload = _reload  # type: ignore[attr-defined]
    SkillsToolset.get_instructions = _patched_get_instructions  # type: ignore[method-assign]
