"""Init 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 InitCommand(ValidatableCommand):
    """Initialize project with git and pre-commit hooks."""

    name = "init"
    alias = "i"
    description = "Initialize project with git and pre-commit hooks"
    command_type = CommandType.UTIL

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

        Args:
            context: Execution context

        Returns
        -------
            True if validation passes, False otherwise
        """
        # Always valid - can initialize anywhere
        return True

    def _init_git_repo(self, context: ExecutionContext) -> bool:
        """Initialize git repository.

        Args:
            context: Execution context

        Returns
        -------
            True if successful, False otherwise
        """
        try:
            # Check if already a git repo
            result = execute_command_with_context(["git", "rev-parse", "--git-dir"], context)

            if result.success:
                self.logger.info("Git repository already initialized")
                return True

            self.logger.info("Initializing git repository...")
            result = execute_command_with_context(["git", "init"], context)

            if result.success:
                self.logger.info("Git repository initialized")
                return True
            self.logger.error("Failed to initialize git repository")
            return False

        except Exception as e:
            self.logger.error(f"Git init failed: {e}")
            return False

    def _setup_precommit(self, context: ExecutionContext) -> bool:
        """Set up pre-commit hooks.

        Args:
            context: Execution context

        Returns
        -------
            True if successful, False otherwise
        """
        try:
            # Check if pre-commit is available
            result = execute_command_with_context(["pre-commit", "--version"], context)

            if not result.success:
                self.logger.warning("pre-commit not found")
                self.logger.info("Install with: pip install pre-commit")
                return False

            # Check if .pre-commit-config.yaml exists
            config_file = context.cwd / ".pre-commit-config.yaml"
            if not config_file.exists():
                self.logger.info("Creating basic .pre-commit-config.yaml...")
                config_content = """repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.1.6
    hooks:
      - id: ruff
        args: [--fix, --exit-non-zero-on-fix]
      - id: ruff-format
"""
                config_file.write_text(config_content, encoding="utf-8")

            # Install pre-commit hooks
            self.logger.info("Installing pre-commit hooks...")
            result = execute_command_with_context(["pre-commit", "install"], context)

            if result.success:
                self.logger.info("Pre-commit hooks installed")
                return True
            self.logger.warning("Failed to install pre-commit hooks")
            return False

        except Exception as e:
            self.logger.error(f"Pre-commit setup failed: {e}")
            return False

    def execute(self, context: ExecutionContext) -> CommandResult:
        """Execute init 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("Initializing project...")

        success_count = 0
        total_steps = 2

        # Initialize git repository
        if self._init_git_repo(context):
            success_count += 1

        # Setup pre-commit hooks
        if self._setup_precommit(context):
            success_count += 1

        self.logger.info(f"Initialization completed: {success_count}/{total_steps} steps successful")

        if success_count == total_steps:
            return CommandResult(success=True, message="Project initialized successfully")
        return CommandResult(
            success=True,
            message=f"Initialized with {success_count}/{total_steps} steps completed",
        )
