"""Controller for shell integration in CLI."""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from portal.interfaces.cli.presenters.output_presenter import OutputPresenter


class ShellController:
    """Controller for shell integration in CLI."""

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

        Args:
            output_presenter: Presenter for output formatting
        """
        self.output_presenter = output_presenter

    async def install_completions(self) -> None:
        """Install shell completions and functions."""
        try:
            from portal.interfaces.cli.shell_integration import ShellIntegration

            success, message = ShellIntegration.install()

            if success:
                self.output_presenter.show_success("Shell integration installed")
                self.output_presenter.show_info(message)

                # Show usage information
                self.output_presenter.console.print()
                self.output_presenter.show_info("Available features:")
                self.output_presenter.console.print("  • Tab completion for portal commands")
                self.output_presenter.console.print("  • 'pw' alias for quick worktree switching")
                self.output_presenter.console.print("  • Automatic directory changing")

                self.output_presenter.console.print()
                self.output_presenter.show_info("Usage examples:")
                self.output_presenter.console.print(
                    "  portal <TAB>        # Show available commands"
                )
                self.output_presenter.console.print(
                    "  portal new <TAB>    # Show branch completion"
                )
                self.output_presenter.console.print(
                    "  pw feature/auth     # Switch to worktree and cd"
                )

            else:
                self.output_presenter.show_error("Failed to install shell integration")
                self.output_presenter.show_error(message)

        except Exception as e:
            self.output_presenter.show_error(f"Failed to install shell integration: {e}")

    async def uninstall_completions(self) -> None:
        """Uninstall shell completions and functions."""
        try:
            from portal.interfaces.cli.shell_integration import ShellIntegration

            success, message = ShellIntegration.uninstall()

            if success:
                self.output_presenter.show_success("Shell integration uninstalled")
                self.output_presenter.show_info(message)
            else:
                self.output_presenter.show_error("Failed to uninstall shell integration")
                self.output_presenter.show_error(message)

        except Exception as e:
            self.output_presenter.show_error(f"Failed to uninstall shell integration: {e}")

    async def show_completion_status(self) -> None:
        """Show current shell completion installation status."""
        try:
            from portal.interfaces.cli.shell_integration import ShellIntegration

            status = ShellIntegration.get_installation_status()

            if status["installed"]:
                self.output_presenter.show_success(
                    f"Shell integration installed for {status['shell']}"
                )
                self.output_presenter.show_info(f"Config file: {status['config_file']}")
            else:
                self.output_presenter.show_info("Shell integration not installed")
                self.output_presenter.show_info("Run 'portal shell install' to enable completions")

            self.output_presenter.show_info(f"Current shell: {status['shell']}")

        except Exception as e:
            self.output_presenter.show_error(f"Failed to check completion status: {e}")

    async def generate_completion_script(self, shell: str) -> None:
        """Generate completion script for specific shell.

        Args:
            shell: Shell type ('bash', 'zsh', 'fish')
        """
        try:
            from portal.interfaces.cli.shell_integration import ShellIntegration

            if shell.lower() == "bash":
                script = ShellIntegration.get_bash_completion()
            elif shell.lower() == "zsh":
                script = ShellIntegration.get_zsh_completion()
            else:
                self.output_presenter.show_error(f"Unsupported shell: {shell}")
                self.output_presenter.show_info("Supported shells: bash, zsh")
                return

            self.output_presenter.show_info(f"Completion script for {shell}:")
            self.output_presenter.console.print()

            # Show the script with syntax highlighting
            from rich.syntax import Syntax

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

        except Exception as e:
            self.output_presenter.show_error(f"Failed to generate completion script: {e}")
