"""Skill tool - progressive disclosure of skill instructions.

When invoked, loads the full SKILL.md content into context.
This implements the "Level 2" loading in the Agent Skills spec:
- Level 1: Metadata (name, description) always in system prompt
- Level 2: Full instructions loaded on-demand via this tool
- Level 3: Resources (scripts/, references/) loaded as needed
"""

from __future__ import annotations

from krim.tools.base import Tool
from krim.skills import Skill, get_skill_content


class SkillTool(Tool):
    """Invoke a skill to load its full instructions.

    Skills use progressive disclosure: only metadata (name, description)
    is loaded initially. Call this tool to load full instructions.
    """

    name = "skill"
    description = "Invoke a skill by name to load its full instructions"

    # Injected by __main__.py before agent starts
    _skills: dict[str, Skill] = {}

    @classmethod
    def configure(cls, skills: dict[str, Skill]):
        """Configure available skills. Called once at startup."""
        cls._skills = skills

    def schema(self) -> dict:
        skill_names = list(self._skills.keys()) if self._skills else ["(none)"]
        return {
            "name": self.name,
            "description": self.description,
            "input_schema": {
                "type": "object",
                "properties": {
                    "skill_name": {
                        "type": "string",
                        "description": f"Name of the skill to invoke. Available: {', '.join(skill_names)}",
                    },
                    "args": {
                        "type": "string",
                        "description": "Optional arguments to pass to the skill (replaces $ARGUMENTS in skill content)",
                        "default": "",
                    },
                },
                "required": ["skill_name"],
            },
        }

    def run(self, skill_name: str, args: str = "") -> str:
        if not self._skills:
            return "error: no skills available"

        if skill_name not in self._skills:
            available = ", ".join(self._skills.keys())
            return f"error: skill '{skill_name}' not found. available: {available}"

        skill = self._skills[skill_name]
        content = get_skill_content(skill)

        # Replace $ARGUMENTS placeholder if present
        if "$ARGUMENTS" in content:
            content = content.replace("$ARGUMENTS", args)
        elif args:
            # Append args if no placeholder
            content += f"\n\nARGUMENTS: {args}"

        # Return formatted instruction block
        return f"""# Skill: {skill.name}

{content}

---
Skill loaded. Follow the instructions above to complete the task."""
