"""Skill command for managing skills"""

from diona.project.cli.commands.base import Command
from diona.project.agent.globals import list_all_skills, get_skill, get_global_skills, SkillSource


class SkillCommand(Command):
    name = "skill"
    description = "Manage skills"
    
    def execute(self, args):
        if not args:
            return self._show_help()
        
        action = args[0]
        
        if action in ("-h", "--help"):
            return self._show_help()
        elif action == "list":
            return self._list_skills()
        elif action == "get":
            return self._get_skill(args[1:])
        elif action == "info":
            return self._get_skill(args[1:])
        elif action == "check":
            return self._check_skill(args[1:])
        else:
            print(f"Unknown action: {action}")
            return self._show_help()
    
    def _show_help(self):
        help_text = """Usage: skill <action> [options]

Actions:
  list                           List all available skills
  get <name>                     Get skill details
  info <name>                    Get skill details (alias for get)
  check <name>                   Check skill requirements

Examples:
  skill list
  skill get nano-pdf
  skill check nano-pdf"""
        print(help_text)
        return False
    
    def _list_skills(self):
        skills = list_all_skills()
        
        if not skills:
            print("No skills found.")
            return False
        
        builtin = [s for s in skills if s.source == SkillSource.BUILTIN]
        user = [s for s in skills if s.source == SkillSource.USER]
        
        print(f"=== Skills ({len(skills)} total) ===\n")
        
        if builtin:
            print(f"Built-in ({len(builtin)}):")
            for s in builtin:
                print(f"  - {s.name}:")
                print(f"    {s.description}")
            print()
        
        if user:
            print(f"User ({len(user)}):")
            for s in user:
                print(f"  - {s.name}:")
                print(f"    {s.description}")
        
        gs = get_global_skills()
        print(f"\nUser skills directory: {gs.user_dir}")
        
        return False
    
    def _get_skill(self, args):
        if not args:
            print("Usage: skill get <name>")
            return False
        
        name = args[0]
        skill = get_skill(name)
        
        if not skill:
            print(f"Skill '{name}' not found")
            return False
        
        source_label = "built-in" if skill.metadata.source == SkillSource.BUILTIN else "user"
        
        print(f"=== Skill: {skill.metadata.name} ({source_label}) ===\n")
        print(f"Description:")
        print(f"  {skill.metadata.description}\n")
        
        if skill.metadata.extra:
            print("Extra metadata:")
            import json
            for key, value in skill.metadata.extra.items():
                print(f"  {key}: {json.dumps(value)[:100]}")
            print()
        
        refs = skill.list_references()
        if refs:
            print(f"References ({len(refs)}):")
            for r in refs:
                print(f"  - {r}")
            print()
        
        scripts = skill.list_scripts()
        if scripts:
            print(f"Scripts ({len(scripts)}):")
            for s in scripts:
                print(f"  - {s}")
            print()
        
        ok, missing = skill.check_requirements()
        if not ok:
            print(f"⚠️ Requirements NOT MET:")
            for m in missing:
                print(f"  - {m}")
        else:
            print("✓ Requirements met")
        
        print("\n--- Content ---")
        print(skill.content)
        
        return False
    
    def _check_skill(self, args):
        if not args:
            print("Usage: skill check <name>")
            return False
        
        name = args[0]
        skill = get_skill(name)
        
        if not skill:
            print(f"Skill '{name}' not found")
            return False
        
        ok, missing = skill.check_requirements()
        
        if missing:
            print(f"⚠️ Skill '{name}' requirements NOT MET:")
            for m in missing:
                print(f"  - {m}")
        else:
            print(f"✓ Skill '{name}' requirements are satisfied.")
        
        return False
