"""Activate command implementation for MakePython."""

from __future__ import annotations

import os
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


IS_WINDOWS = os.name == "nt"


class ActivateCommand(ValidatableCommand):
    """Activate virtual environment."""

    name = "activate"
    alias = "a"
    description = "Activate virtual environment"
    command_type = CommandType.BUILD

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

        Args:
            context: Execution context

        Returns
        -------
            True if validation passes, False otherwise
        """
        venv_path = context.cwd / ".venv"

        if IS_WINDOWS:
            activate_script = venv_path / "Scripts" / "activate.bat"
        else:
            activate_script = venv_path / "bin" / "activate"

        if not activate_script.exists():
            self.logger.error(f"Virtual environment activation script not found: {activate_script}")
            return False

        return True

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

        Args:
            context: Execution context

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

        venv_path = context.cwd / ".venv"

        if IS_WINDOWS:
            activate_script = venv_path / "Scripts" / "activate.bat"
            try:
                # Run the activation script in a subprocess
                result = execute_command_with_context([str(activate_script)], context)
                if result.success:
                    self.logger.info("Virtual environment activated successfully")
                else:
                    self.logger.error(f"Failed to activate virtual environment: {result.message}")
                return result
            except Exception as e:
                self.logger.error(f"Failed to activate virtual environment: {e}")
                return CommandResult(success=False, message=str(e))
        else:
            activate_script = venv_path / "bin" / "activate"
            try:
                # For Unix-like systems, we need to source the script
                # We'll run a shell that sources the script and runs a command
                result = execute_command_with_context(
                    ["bash", "-c", f"source '{activate_script}' && echo 'Activated'"], context
                )
                if result.success:
                    self.logger.info("Virtual environment activated successfully")
                else:
                    self.logger.error(f"Failed to activate virtual environment: {result.message}")
                return result
            except Exception as e:
                self.logger.error(f"Failed to activate virtual environment: {e}")
                return CommandResult(success=False, message=str(e))
