"""Dist command implementation for MakePython."""

from __future__ import annotations

from typing import TYPE_CHECKING

from ...core.executor import execute_command_with_context
from ...interfaces.command import CommandResult, CommandType, ValidatableCommand

if TYPE_CHECKING:
    from ...core.context import ExecutionContext


class DistCommand(ValidatableCommand):
    """Generate distribution package with complete workflow."""

    name = "dist"
    alias = "di"
    description = "Generate distribution package with complete workflow"
    command_type = CommandType.BUILD

    def validate(self, context: ExecutionContext) -> bool:
        """Validate dist command prerequisites.

        Args:
            context: Execution context

        Returns
        -------
            True if validation passes, False otherwise
        """
        # Check if pyproject.toml exists
        pyproject_path = context.cwd / "pyproject.toml"
        if not pyproject_path.exists():
            self.logger.error("pyproject.toml not found")
            return False

        # Check if build tool is available
        build_tool = context.get_build_tool()
        if not build_tool:
            self.logger.error("Could not determine build tool")
            return False

        return True

    def execute(self, context: ExecutionContext) -> CommandResult:
        """Execute dist command.

        Args:
            context: Execution context

        Returns
        -------
            CommandResult with execution status
        """
        if not self.validate(context):
            return CommandResult(success=False, message="Validation failed")

        try:
            build_tool = context.get_build_tool()
            if not build_tool:
                return CommandResult(success=False, message="Could not determine build tool")

            self.logger.info(f"Generating distribution package using {build_tool.value}...")

            # Execute build command to create distribution package
            cmd = [build_tool.value, "build"]
            result = execute_command_with_context(cmd, context)

            if result.success:
                self.logger.info("Distribution package generated successfully!")

                # List generated files
                dist_dir = context.cwd / "dist"
                if dist_dir.exists():
                    dist_files = list(dist_dir.glob("*"))
                    if dist_files:
                        self.logger.info("Generated files:")
                        for file in dist_files:
                            self.logger.info(f"  - {file.name}")

                return CommandResult(
                    success=True,
                    message="Distribution package generated successfully",
                    data={"dist_dir": str(dist_dir)},
                )
            self.logger.error(f"Build failed with exit code {result.exit_code}")
            return CommandResult(success=False, message=f"Build failed: {result.message}")

        except Exception as e:
            self.logger.exception(f"Dist command failed: {e}")
            return CommandResult(success=False, message=str(e))
