"""Sub agent command for calling sub-agents"""

import os

from .base import BuiltinCommand
from diona.project.agent import get_core_agent, get_sub_agent_registry


class SubCommand(BuiltinCommand):
    """Sub-agent command for explicitly calling a sub-agent"""
    name = "sub"
    description = "Call a specific sub-agent"
    
    def execute(self, args):
        """Execute sub-agent command
        
        Args:
            args: Command arguments - should be in format "agent_name input"
        """
        if not args:
            self._print_help()
            return False
        
        agent_name = args[0]
        user_input = " ".join(args[1:]) if len(args) > 1 else ""
        
        registry = get_sub_agent_registry()
        agent_info = registry.get(agent_name)
        
        if not agent_info:
            print(f"Sub-agent '{agent_name}' not found")
            print(f"Available sub-agents:")
            for agent in registry.list_all():
                print(f"  - {agent.name}: {agent.description}")
            return False
        
        try:
            result = agent_info.callable(user_input)
            print(result)
        except Exception as e:
            print(f"Error executing sub-agent: {e}")
        
        return False
    
    def _print_help(self):
        """Print help message"""
        registry = get_sub_agent_registry()
        agents = registry.list_all()
        
        print("Usage: /sub <agent_name> [input]")
        print("Call a specific sub-agent")
        print("")
        
        if agents:
            print("Available sub-agents:")
            for agent in agents:
                print(f"  {agent.name}: {agent.description}")
        else:
            print("No sub-agents registered")


sub_command = SubCommand()
