"""Controller for hook management in CLI."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from portal.interfaces.cli.utils.error_handler import ErrorHandler
from portal.interfaces.cli.utils.input_validator import InputValidator

if TYPE_CHECKING:
    from portal.core.services.hook_service import HookService
    from portal.interfaces.cli.presenters.output_presenter import OutputPresenter


class HookController:
    """Controller for hook management in CLI."""

    def __init__(self, hook_service: HookService, output_presenter: OutputPresenter) -> None:
        """Initialize the hook controller.

        Args:
            hook_service: Service for hook operations
            output_presenter: Presenter for output formatting
        """
        self.hook_service = hook_service
        self.output_presenter = output_presenter
        self.error_handler = ErrorHandler(output_presenter)

    async def list_hooks(self) -> None:
        """List all configured hooks."""
        self.output_presenter.show_info("Hook listing is managed via configuration files")
        self.output_presenter.show_info(
            "Check your project's .portal file or global ~/.portal/config.yml"
        )
        self.output_presenter.show_info("Example hook configuration:")
        from rich.syntax import Syntax

        example_yaml = """hooks:
  post_create:
    - type: command
      config:
        command: "npm install"
      condition: "file_exists:package.json"
    - type: copy
      config:
        from: ".env.example"
        to: ".env" """

        syntax = Syntax(example_yaml, "yaml", theme="monokai", line_numbers=False)
        self.output_presenter.console.print(syntax)

    async def run_hooks(self, stage: str, dry_run: bool = False) -> None:  # noqa: ARG002
        """Manually run hooks for a specific stage.

        Args:
            stage: Hook stage to run
            dry_run: Whether to show what would be executed without running
        """
        # Validate hook stage
        validated_stage = InputValidator.validate_hook_stage(stage)
        if not validated_stage:
            self.output_presenter.show_error(f"Invalid hook stage: {stage}")
            self.output_presenter.show_info(
                "Valid stages: post_create, pre_delete, pre_switch, post_switch"
            )
            return

        async def run_operation() -> Any:
            if dry_run:
                self.output_presenter.show_info(f"Dry run: would execute {validated_stage} hooks")
                # For dry run, just show what would happen
                return {"success": True, "executed_hooks": [], "errors": [], "warnings": []}
            else:
                self.output_presenter.show_info(f"Running {validated_stage} hooks...")
                # For now, return placeholder since we don't have a worktree context
                return {
                    "success": False,
                    "executed_hooks": [],
                    "errors": ["Hook execution requires worktree context"],
                    "warnings": [],
                }

        result = await self.error_handler.handle_operation(
            run_operation, f"run {validated_stage} hooks"
        )

        if result:
            self.error_handler.handle_service_result(result)

    async def validate_hooks(self) -> None:
        """Validate all configured hooks."""
        self.output_presenter.show_info(
            "Hook validation is performed automatically during execution"
        )
        self.output_presenter.show_info("Invalid hooks are skipped with appropriate error messages")
        self.output_presenter.show_success(
            "To test your hooks, use: portal hooks run <stage> --dry-run"
        )

    async def enable_hook(self, hook_name: str) -> None:
        """Enable a specific hook.

        Args:
            hook_name: Name of the hook to enable
        """
        self.output_presenter.show_info("Hook management is done via configuration files")
        self.output_presenter.show_info(
            f"To enable '{hook_name}', add it to your .portal or config.yml file"
        )
        self.output_presenter.show_info(
            "Dynamic hook management is not supported for security reasons"
        )

    async def disable_hook(self, hook_name: str) -> None:
        """Disable a specific hook.

        Args:
            hook_name: Name of the hook to disable
        """
        self.output_presenter.show_info("Hook management is done via configuration files")
        self.output_presenter.show_info(
            f"To disable '{hook_name}', remove it from your .portal or config.yml file"
        )
        self.output_presenter.show_info(
            "Dynamic hook management is not supported for security reasons"
        )
