"""Command registry center"""

from .command_manager import CommandManager
from .models import CommandModel, CommandParameter


class CommandRegistry:
    """Command registry singleton for managing commands"""
    _instance = None
    
    def __new__(cls):
        """Create a singleton instance"""
        if cls._instance is None:
            cls._instance = super(CommandRegistry, cls).__new__(cls)
            cls._instance._command_manager = CommandManager()
            # Register default commands
            cls._instance._register_default_commands()
            # Load aliases from alias.py
            cls._instance._load_aliases()
        return cls._instance
    
    def _load_aliases(self):
        """Load aliases from alias.py"""
        try:
            # Try to import alias.py from command directory
            from . import alias
            if hasattr(alias, 'ALIAS_NAME'):
                aliases = alias.ALIAS_NAME
                if isinstance(aliases, dict):
                    for alias_name, command_name in aliases.items():
                        self._command_manager.register_alias(alias_name, command_name)
        except ImportError:
            # alias.py not found, skip
            pass
    
    def _register_default_commands(self):
        """Register default commands"""
        # Register fakedelete command
        from diona.tools.fakedelete.command import FakeDeleteCommand
        if not self._command_manager.has_command(FakeDeleteCommand.name):
            self._command_manager.register_command(FakeDeleteCommand)
        
        # Register fakeinstall command
        from diona.tools.fakeinstall.command import FakeInstallCommand
        if not self._command_manager.has_command(FakeInstallCommand.name):
            self._command_manager.register_command(FakeInstallCommand)
        
        # Register SimpleCLI command
        from diona.ai.client.simplecli.command import SimpleCLICommand
        if not self._command_manager.has_command(SimpleCLICommand.name):
            self._command_manager.register_command(SimpleCLICommand)
    
    def register_command(self, command: CommandModel):
        """Register a command
        
        Args:
            command: Command model to register
        """
        if not self._command_manager.has_command(command.name):
            self._command_manager.register_command(command)
    
    def register_alias(self, alias: str, command_name: str):
        """Register an alias for a command
        
        Args:
            alias: Alias name
            command_name: Real command name
        """
        self._command_manager.register_alias(alias, command_name)
    
    def get_command_manager(self):
        """Get the command manager instance
        
        Returns:
            CommandManager instance
        """
        return self._command_manager
