"""Build command implementation for MakePython."""

from __future__ import annotations

from typing import TYPE_CHECKING

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

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


class BuildCommand(ValidatableCommand):
    """Build the project package."""

    name = "build"
    alias = "b"
    description = "Build the project package"
    command_type = CommandType.BUILD

    def validate(self, context: ExecutionContext) -> bool:
        """Validate build 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 in current directory")
            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 from pyproject.toml")
            return False

        return True

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

        Args:
            context: Execution context

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

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

        self.logger.info(f"Building project with {build_tool.value}...")

        cmd = [build_tool.value, "build"]
        executor = CommandExecutor(context)
        result = executor.execute_shell_command(cmd)

        if result.success:
            self.logger.info("Build completed successfully!")
        else:
            self.logger.error(f"Build failed with exit code {result.exit_code}")

        return result
