"""Lint 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 LintCommand(ValidatableCommand):
    """Lint code using Ruff with auto-fix."""

    name = "lint"
    alias = "l"
    description = "Lint code using Ruff with auto-fix"
    command_type = CommandType.UTIL

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

        Args:
            context: Execution context

        Returns
        -------
            True if validation passes, False otherwise
        """
        # Check if ruff is available
        result = execute_command_with_context(["ruff", "--version"], context)
        if not result.success:
            self.logger.warning("Ruff not found, but will attempt to run anyway")

        return True

    def execute(self, context: ExecutionContext) -> CommandResult:
        """Execute lint 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("Running Ruff linter with auto-fix...")

        # First try to fix issues
        self.logger.info("Attempting to auto-fix issues...")
        fix_result = execute_command_with_context(["ruff", "check", ".", "--fix"], context)

        if fix_result.success:
            self.logger.info("Auto-fix completed")
        else:
            self.logger.warning("Auto-fix encountered issues")

        # Then show remaining issues
        self.logger.info("Checking for remaining issues...")
        check_result = execute_command_with_context(["ruff", "check", "."], context)

        if check_result.success:
            self.logger.info("No lint issues found!")
            return CommandResult(success=True, message="No lint issues found")
        self.logger.info("Lint check completed with issues")
        return CommandResult(
            success=True,
            message="Lint check completed. See output for details.",
            data={"output": check_result.data.get("stdout", "") if check_result.data else ""},
        )
