"""Module command registry for managing registered commands and aliases"""

import threading
from typing import Dict, Optional


class CommandModel:
    """Command model interface"""
    name: str


class ModuleCommandRegistry:
    """Singleton registry for managing module commands and aliases"""

    _instance: Optional["ModuleCommandRegistry"] = None

    def __new__(cls) -> "ModuleCommandRegistry":
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._commands: Dict[str, CommandModel] = {}
            cls._instance._aliases: Dict[str, str] = {}
            cls._instance._lock = threading.RLock()
            cls._instance._load_aliases()
            cls._instance._register_default_commands()
        return cls._instance

    def _load_aliases(self):
        """Load aliases from alias configuration"""
        try:
            # Try to import alias configuration
            from diona.project.command import alias
            if hasattr(alias, 'ALIAS_NAME'):
                aliases = alias.ALIAS_NAME
                if isinstance(aliases, dict):
                    for alias_name, command_name in aliases.items():
                        self.register_alias(alias_name, command_name)
        except ImportError:
            # alias module 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.has_command(FakeDeleteCommand.name):
        #     self.register_command(FakeDeleteCommand)
        
        # Register fakeinstall command
        # from diona.tools.fakeinstall.command import FakeInstallCommand
        # if not self.has_command(FakeInstallCommand.name):
        #     self.register_command(FakeInstallCommand)
        
        # Register SimpleCLI command
        # from diona.ai.client.simplecli.command import SimpleCLICommand
        # if not self.has_command(SimpleCLICommand.name):
        #     self.register_command(SimpleCLICommand)
        
        # Register sensitive module commands
        try:
            import diona.system.sensitive.register
            print("Registered sensitive module commands")
        except Exception as e:
            print(f"Warning: Failed to register sensitive module commands: {e}")

    def register_command(self, command: CommandModel):
        """Register a command

        Args:
            command: Command model to register
        """
        with self._lock:
            self._commands[command.name] = 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
        """
        with self._lock:
            self._aliases[alias] = command_name

    def get_command(self, name: str) -> Optional[CommandModel]:
        """Get a registered command

        Args:
            name: Command name or alias

        Returns:
            Command model or None if not found
        """
        with self._lock:
            # Check if name is an alias
            if name in self._aliases:
                name = self._aliases[name]
            return self._commands.get(name)

    def get_real_command_name(self, name: str) -> Optional[str]:
        """Get the real command name for a given name or alias

        Args:
            name: Command name or alias

        Returns:
            Real command name or None if not found
        """
        with self._lock:
            # Check if name is an alias
            if name in self._aliases:
                return self._aliases[name]
            # Check if name is a real command
            if name in self._commands:
                return name
            return None

    def list_commands(self) -> Dict[str, CommandModel]:
        """List all registered commands

        Returns:
            Dictionary of command names to command models
        """
        with self._lock:
            return self._commands.copy()

    def list_aliases(self) -> Dict[str, str]:
        """List all registered aliases

        Returns:
            Dictionary of aliases to real command names
        """
        with self._lock:
            return self._aliases.copy()

    def has_command(self, name: str) -> bool:
        """Check if a command is registered

        Args:
            name: Command name or alias

        Returns:
            True if command is registered, False otherwise
        """
        with self._lock:
            # Check if name is an alias
            if name in self._aliases:
                return self._aliases[name] in self._commands
            # Check if name is a real command
            return name in self._commands

    def get_command_manager(self):
        """Get the command manager instance (backward compatibility)

        Returns:
            self, since this class now combines both registry and manager functionality
        """
        return self


def get_module_command_registry() -> ModuleCommandRegistry:
    """Get the singleton module command registry

    Returns:
        ModuleCommandRegistry instance
    """
    return ModuleCommandRegistry()
