"""Skills tool for OpenAI Agent - allows AI to selectively load skills"""

import json
from agents import function_tool

from diona.project.agent.globals import (
    list_all_skills,
    get_skill,
    get_skill_reference,
    get_skill_script,
    check_skill_requirements,
    SkillSource,
)


@function_tool
async def skills_tool(action: str, name: str = None, reference: str = None, script: str = None) -> str:
    """Manage and retrieve skills for AI assistance.
    
    Skills are modular knowledge packages that extend the AI's capabilities. Each skill
    consists of SKILL.md (metadata + instructions) and optional bundled resources:
    - references/: Documentation to load into context when needed
    - scripts/: Executable code for deterministic tasks
    - assets/: Files for output (templates, icons, etc.)
    
    Built-in skills: Package skills directory
    User skills: ~/.diona/user/agent/skills
    
    Args:
        action: One of "list", "get", "references", "scripts", "check"
        name: Skill name (required for all actions except "list")
        reference: Reference file name (for "references" action)
        script: Script file name (for "scripts" action)
    
    Returns:
        Formatted skill information based on action
    """
    if action == "list":
        return _handle_list()
    
    elif action == "get":
        return _handle_get(name)
    
    elif action == "references":
        return _handle_references(name, reference)
    
    elif action == "scripts":
        return _handle_scripts(name, script)
    
    elif action == "check":
        return _handle_check(name)
    
    else:
        return f"Error: Unknown action '{action}'. Use: list, get, references, scripts, check"


def _handle_list() -> str:
    """Handle list action - show all available skills"""
    skills = list_all_skills()
    
    if not skills:
        return "No skills found."
    
    builtin = [s for s in skills if s.source == SkillSource.BUILTIN]
    user = [s for s in skills if s.source == SkillSource.USER]
    
    lines = [f"Available Skills ({len(skills)} total: {len(builtin)} built-in, {len(user)} user):\n"]
    
    if builtin:
        lines.append("### Built-in Skills")
        for s in builtin:
            lines.append(f"- **{s.name}**: {s.description}")
            if s.extra:
                extra_info = ", ".join(f"{k}" for k in s.extra.keys())
                lines.append(f"  - Extra: {extra_info}")
        lines.append("")
    
    if user:
        lines.append("### User Skills")
        for s in user:
            lines.append(f"- **{s.name}**: {s.description}")
            if s.extra:
                extra_info = ", ".join(f"{k}" for k in s.extra.keys())
                lines.append(f"  - Extra: {extra_info}")
        lines.append("")
    
    lines.append("Use 'skills_tool' with action='get' and name='<skill-name>' to load a skill.")
    lines.append("Use 'skills_tool' with action='check' and name='<skill-name>' to check requirements.")
    
    return "\n".join(lines)


def _handle_get(name: str) -> str:
    """Handle get action - load skill content"""
    if not name:
        return "Error: Skill name is required for 'get' action"
    
    skill = get_skill(name)
    
    if not skill:
        return f"Error: Skill '{name}' not found"
    
    source_label = "built-in" if skill.metadata.source == SkillSource.BUILTIN else "user"
    
    lines = [
        f"# Skill: {skill.metadata.name} ({source_label})",
        f"\n**Description**: {skill.metadata.description}",
    ]
    
    if skill.metadata.extra.get("homepage"):
        lines.append(f"**Homepage**: {skill.metadata.extra.get('homepage')}")
    
    refs = skill.list_references()
    if refs:
        lines.append(f"\n**References** ({len(refs)} files):")
        for r in refs:
            lines.append(f"  - {r}")
    
    scripts = skill.list_scripts()
    if scripts:
        lines.append(f"\n**Scripts** ({len(scripts)} files):")
        for s in scripts:
            lines.append(f"  - {s}")
    
    ok, missing = skill.check_requirements()
    if not ok:
        lines.append(f"\n**⚠️ Requirements NOT MET**: {', '.join(missing)}")
    else:
        lines.append("\n**✓ Requirements met**")
    
    lines.append(f"\n---\n{skill.content}")
    
    return "\n".join(lines)


def _handle_references(name: str, reference: str = None) -> str:
    """Handle references action - list or get reference content"""
    if not name:
        return "Error: Skill name is required for 'references' action"
    
    skill = get_skill(name)
    
    if not skill:
        return f"Error: Skill '{name}' not found"
    
    refs = skill.list_references()
    
    if not refs:
        return f"Skill '{name}' has no references."
    
    if reference:
        content = skill.get_reference(reference)
        if content is None:
            return f"Error: Reference '{reference}' not found in skill '{name}'"
        return f"# Reference: {reference} (from skill: {name})\n\n{content}"
    else:
        lines = [f"References in skill '{name}':"]
        for r in refs:
            lines.append(f"  - {r}")
        lines.append(f"\nUse action='references', name='{name}', reference='<file>' to get content.")
        return "\n".join(lines)


def _handle_scripts(name: str, script: str = None) -> str:
    """Handle scripts action - list or get script content"""
    if not name:
        return "Error: Skill name is required for 'scripts' action"
    
    skill = get_skill(name)
    
    if not skill:
        return f"Error: Skill '{name}' not found"
    
    scripts = skill.list_scripts()
    
    if not scripts:
        return f"Skill '{name}' has no scripts."
    
    if script:
        content = skill.get_script(script)
        if content is None:
            return f"Error: Script '{script}' not found in skill '{name}'"
        return f"# Script: {script} (from skill: {name})\n\n{content}"
    else:
        lines = [f"Scripts in skill '{name}':"]
        for s in scripts:
            lines.append(f"  - {s}")
        lines.append(f"\nUse action='scripts', name='{name}', script='<file>' to get content.")
        return "\n".join(lines)


def _handle_check(name: str) -> str:
    """Handle check action - verify skill requirements"""
    if not name:
        return "Error: Skill name is required for 'check' action"
    
    ok, missing = check_skill_requirements(name)
    
    if missing:
        return f"⚠️ Skill '{name}' requirements NOT MET:\n" + "\n".join(f"  - {m}" for m in missing)
    else:
        return f"✓ Skill '{name}' requirements are satisfied."
