"""Command auto-importer and registry manager."""

import importlib
from typing import Dict, List

from pytola.core.logger import get_logger

from .base import CommandRegistry

logger = get_logger(__name__)


# Command modules that contain registered commands
# NOTE: These are legacy modules; new commands should be in commands.impl
COMMAND_MODULES = [
    "pytola.dev.makepython.commands.build",
    "pytola.dev.makepython.commands.test",
    "pytola.dev.makepython.commands.publish",
    "pytola.dev.makepython.commands.version",
    "pytola.dev.makepython.commands.utility",
    "pytola.dev.makepython.commands.detect",
    "pytola.dev.makepython.commands.token",
]

# Module directories for automatic discovery
COMMAND_DIRS = ["build", "test", "publish", "version", "utility", "detect", "token"]


class CommandAutoLoader:
    """Auto-loads command modules and registers their commands."""

    @classmethod
    def load_all_commands(cls) -> Dict[str, List[str]]:
        """Load all command modules and return registration summary."""
        loaded_modules = []
        failed_modules = []

        for module_name in COMMAND_MODULES:
            try:
                importlib.import_module(module_name)
                loaded_modules.append(module_name)
                logger.debug(f"Loaded command module: {module_name}")
            except Exception as e:
                failed_modules.append(module_name)
                logger.warning(f"Failed to load command module {module_name}: {e}")

        # Report summary
        logger.info(f"Loaded {len(loaded_modules)} command modules successfully")
        if failed_modules:
            logger.warning(f"Failed to load {len(failed_modules)} command modules: {failed_modules}")

        # Return summary by command type
        return cls._summarize_commands()

    @classmethod
    def _summarize_commands(cls) -> Dict[str, List[str]]:
        """Get summary of all registered commands by type."""
        command_types = {}

        # Get all registered commands (excluding aliases to avoid duplicates)
        registered_names = CommandRegistry.list_commands()
        for cmd_name in registered_names:
            # Get command instance for metadata
            cmd_metadata = CommandRegistry.get_command_metadata(cmd_name)
            if not cmd_metadata:
                logger.warning(f"Unable to fetch command meta: {cmd_name}")
                cmd_info = "-- unavailable Command to fetch metadata --"
            else:
                cmd_info = f"{cmd_name} ({cmd_metadata.alias}) - {cmd_metadata.description}"

            # Group by command type
            cmd_type = cmd_metadata.command_type.name if cmd_metadata else "UNKNOWN"
            if cmd_type not in command_types:
                command_types[cmd_type] = []
            command_types[cmd_type].append(cmd_info)

        return command_types

    @classmethod
    def get_command_help(cls) -> str:
        """Generate help text for all registered commands."""
        from .base import CommandType

        command_types = cls._summarize_commands()
        help_lines = ["Available Commands:", ""]

        # Sort command types for consistent output
        type_order = [
            CommandType.BUILD.name,
            CommandType.TEST.name,
            CommandType.PUBLISH.name,
            CommandType.BUMP_VERSION.name,
            CommandType.TOKEN.name,
            CommandType.CLEAN.name,
            CommandType.UTIL.name,
        ]

        for type_name in type_order:
            if type_name in command_types:
                help_lines.append(f"{type_name.title()} Commands:")
                for cmd_info in sorted(command_types[type_name]):
                    help_lines.append(f"  {cmd_info}")
                help_lines.append("")

        # Add any unknown types
        for type_name in sorted(command_types.keys()):
            if type_name not in type_order:
                help_lines.append(f"{type_name.title()} Commands:")
                for cmd_info in sorted(command_types[type_name]):
                    help_lines.append(f"  {cmd_info}")
                help_lines.append("")

        return "\n".join(help_lines)


def load_commands() -> Dict[str, List[str]]:
    """Load all commands."""
    return CommandAutoLoader.load_all_commands()
