"""Controller for external integration operations in CLI."""

from __future__ import annotations

from typing import TYPE_CHECKING

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

if TYPE_CHECKING:
    from portal.core.services.integration_service import IntegrationService
    from portal.interfaces.cli.presenters.integration_presenter import IntegrationPresenter
    from portal.interfaces.cli.presenters.output_presenter import OutputPresenter


class IntegrationController:
    """Controller for external integration operations in CLI."""

    def __init__(
        self,
        integration_service: IntegrationService,
        integration_presenter: IntegrationPresenter,
        output_presenter: OutputPresenter,
    ) -> None:
        """Initialize the integration controller.

        Args:
            integration_service: Service for integration operations
            integration_presenter: Presenter for integration UI
            output_presenter: Presenter for output formatting
        """
        self.integration_service = integration_service
        self.integration_presenter = integration_presenter
        self.output_presenter = output_presenter
        self.error_handler = ErrorHandler(output_presenter)

    async def show_integration_status(self) -> None:
        """Display status of all external integrations."""
        try:
            status = self.integration_service.get_all_integrations_status()
            self.integration_presenter.show_integration_status(status)
        except Exception as e:
            self.output_presenter.show_error(f"Failed to get integration status: {str(e)}")

    async def list_available_integrations(self) -> None:
        """List all available external integrations."""
        try:
            terminals = self.integration_service.get_available_terminals()
            editors = self.integration_service.get_available_editors()

            self.integration_presenter.show_available_integrations(
                terminals=terminals, editors=editors
            )
        except Exception as e:
            self.output_presenter.show_error(f"Failed to list integrations: {str(e)}")

    async def interactive_integration_menu(self) -> None:
        """Show interactive integration management menu."""
        while True:
            try:
                choice = self.integration_presenter.show_integration_menu()

                if choice is None or choice == "quit":
                    break
                elif choice == "status":
                    await self.show_integration_status()
                elif choice == "list":
                    await self.list_available_integrations()
                elif choice == "test":
                    await self.test_integrations()
                elif choice == "recommendations":
                    await self.show_recommendations()
                else:
                    self.output_presenter.show_error("Invalid choice")

            except Exception as e:
                self.output_presenter.show_error(f"Integration menu error: {str(e)}")

    async def test_integrations(self) -> None:
        """Test all available integrations."""
        try:
            status = self.integration_service.get_all_integrations_status()
            self.integration_presenter.show_integration_test_results(status)
        except Exception as e:
            self.output_presenter.show_error(f"Failed to test integrations: {str(e)}")

    async def show_recommendations(self) -> None:
        """Show integration recommendations."""
        try:
            recommended_editor = self.integration_service.get_recommended_editor()
            recommended_terminal = self.integration_service.get_recommended_terminal()

            self.integration_presenter.show_recommendations(
                editor=recommended_editor, terminal=recommended_terminal
            )
        except Exception as e:
            self.output_presenter.show_error(f"Failed to get recommendations: {str(e)}")

    async def show_integration_summary(self) -> None:
        """Show a summary of integration status."""
        try:
            if not self.integration_service.has_any_integrations():
                self.output_presenter.show_warning(
                    "No external integrations are currently available"
                )
                return

            counts = self.integration_service.count_available_integrations()
            self.integration_presenter.show_integration_summary(counts)

        except Exception as e:
            self.output_presenter.show_error(f"Failed to show integration summary: {str(e)}")
