"""Clean command implementation for MakePython."""

from __future__ import annotations

import shutil
from pathlib import Path
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 CleanCommand(ValidatableCommand):
    """Clean build artifacts and temporary files."""

    name = "clean"
    alias = "c"
    description = "Clean build artifacts and temporary files"
    command_type = CommandType.CLEAN

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

        Args:
            context: Execution context

        Returns
        -------
            True if validation passes, False otherwise
        """
        # Always valid - clean can run even without pyproject.toml
        return True

    def _clean_directory(self, path: Path) -> bool:
        """Clean a directory or file.

        Args:
            path: Path to clean

        Returns
        -------
            True if successfully cleaned, False otherwise
        """
        try:
            if not path.exists():
                return False

            if path.is_dir():
                shutil.rmtree(path)
                self.logger.debug(f"Removed directory: {path}")
            else:
                path.unlink()
                self.logger.debug(f"Removed file: {path}")

            return True
        except Exception as e:
            self.logger.warning(f"Failed to clean {path.name}: {e}")
            return False

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

        Args:
            context: Execution context

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

        self.logger.info("Cleaning build artifacts...")

        root_dir = context.project_root or context.cwd
        cleaned_count = 0
        failed_count = 0

        # Clean common build directories
        targets = ["dist", "build", ".pytest_cache", ".mypy_cache", ".ruff_cache"]

        for target_name in targets:
            target_path = root_dir / target_name
            if self._clean_directory(target_path):
                cleaned_count += 1

        # Clean egg-info directories
        for egg_info in root_dir.glob("*.egg-info"):
            if self._clean_directory(egg_info):
                cleaned_count += 1

        # Clean __pycache__ directories
        for pycache in root_dir.rglob("__pycache__"):
            if self._clean_directory(pycache):
                cleaned_count += 1

        # Clean .pyc files
        for pyc_file in root_dir.rglob("*.pyc"):
            if self._clean_directory(pyc_file):
                cleaned_count += 1

        # Try to use build tool's clean command if available
        build_tool = context.get_build_tool()
        if build_tool:
            try:
                cmd = [build_tool.value, "clean"]
                result = execute_command_with_context(cmd, context)
                if result.success:
                    self.logger.debug(f"Build tool {build_tool.value} clean completed")
            except Exception:
                pass  # Ignore errors from build tool clean

        self.logger.info(f"Clean operation completed: {cleaned_count} succeeded, {failed_count} failed")

        return CommandResult(
            success=True,
            message=f"Cleaned {cleaned_count} items",
            data={"cleaned_count": cleaned_count, "failed_count": failed_count},
        )
