"""Terminal UI components for the installation wizard."""

from dataclasses import dataclass

from rich.console import Console
from rich.panel import Panel
from rich.text import Text
import questionary
from questionary import Style

OPTIX_HEADER = """
   ██████╗ ██████╗ ████████╗██╗██╗  ██╗
  ██╔═══██╗██╔══██╗╚══██╔══╝██║╚██╗██╔╝
  ██║   ██║██████╔╝   ██║   ██║ ╚███╔╝
  ██║   ██║██╔═══╝    ██║   ██║ ██╔██╗
  ╚██████╔╝██║        ██║   ██║██╔╝ ██╗
   ╚═════╝ ╚═╝        ╚═╝   ╚═╝╚═╝  ╚═╝

  MCP Server Installation Wizard
"""

QUESTIONARY_STYLE = Style([
    ("qmark", "fg:cyan bold"),
    ("question", "bold"),
    ("answer", "fg:cyan bold"),
    ("pointer", "fg:cyan bold"),
    ("highlighted", "fg:cyan bold"),
    ("selected", "fg:green"),
    ("separator", "fg:gray"),
    ("instruction", "fg:gray"),
])


@dataclass
class AgentChoice:
    """Represents an agent selection choice."""
    name: str
    label: str
    checked: bool = False


class ConsoleUI:
    """Terminal UI handler using rich and questionary."""

    def __init__(self, quiet: bool = False, verbose: bool = False):
        self.console = Console()
        self.quiet = quiet
        self.verbose = verbose

    def show_header(self) -> None:
        if self.quiet:
            return
        self.console.print(Text(OPTIX_HEADER, style="cyan"))

    def info(self, message: str) -> None:
        if self.quiet:
            return
        self.console.print(f"[blue]ℹ[/blue] {message}")

    def success(self, message: str) -> None:
        if self.quiet:
            return
        self.console.print(f"[green]✓[/green] {message}")

    def warn(self, message: str) -> None:
        self.console.print(f"[yellow]⚠[/yellow] {message}")

    def error(self, message: str) -> None:
        self.console.print(f"[red]✗[/red] {message}", style="red")

    def debug(self, message: str) -> None:
        if self.verbose:
            self.console.print(f"[cyan]→[/cyan] {message}")

    def newline(self) -> None:
        if not self.quiet:
            self.console.print()

    def select_agents(self, choices: list[AgentChoice]) -> list[str]:
        """Multi-select agent checkboxes."""
        questions_choices = [
            questionary.Choice(
                title=choice.label,
                value=choice.name,
                checked=choice.checked,
            )
            for choice in choices
        ]

        selected = questionary.checkbox(
            "Select AI agents to configure:",
            choices=questions_choices,
            style=QUESTIONARY_STYLE,
            instruction="(Use arrow keys to move, space to toggle, enter to confirm)",
        ).ask()

        if selected is None:
            raise KeyboardInterrupt()

        if not selected:
            self.warn("Please select at least one agent")
            return self.select_agents(choices)

        return selected

    def select_scope(self) -> str:
        """Single select for installation scope."""
        choices = [
            questionary.Choice(title="Global (user-wide)", value="global"),
            questionary.Choice(title="Local (current project)", value="local"),
        ]

        selected = questionary.select(
            "Select installation scope:",
            choices=choices,
            style=QUESTIONARY_STYLE,
        ).ask()

        if selected is None:
            raise KeyboardInterrupt()

        return selected

    def confirm(self, message: str, default: bool = False) -> bool:
        """Ask for confirmation."""
        result = questionary.confirm(
            message,
            default=default,
            style=QUESTIONARY_STYLE,
        ).ask()

        if result is None:
            raise KeyboardInterrupt()

        return result

    def prompt_password(self, message: str) -> str:
        """Prompt for password/secret input (hidden)."""
        result = questionary.password(
            message,
            style=QUESTIONARY_STYLE,
        ).ask()

        if result is None:
            raise KeyboardInterrupt()

        return result or ""

    def prompt_text(self, message: str, default: str = "") -> str:
        """Prompt for text input."""
        result = questionary.text(
            message,
            default=default,
            style=QUESTIONARY_STYLE,
        ).ask()

        if result is None:
            raise KeyboardInterrupt()

        return result or ""

    def show_completion(
        self,
        agents: list[str],
        scope: str,
        expert_enabled: bool,
    ) -> None:
        """Show final completion panel."""
        self.newline()

        agent_list = "\n".join(f"    • {agent}" for agent in agents)
        expert_status = "[green]enabled[/green]" if expert_enabled else "disabled"

        content = f"""[bold]Configured agents:[/bold]
{agent_list}

[bold]Scope:[/bold] {scope}
[bold]Expert analysis:[/bold] {expert_status}

[bold]Next steps:[/bold]
  1. Restart your AI agent application
  2. Verify installation with: health_check tool
  3. Run your first audit: security_audit tool

[bold]Documentation:[/bold]
  https://github.com/ravnhq/ravn-labs-optix-2#readme"""

        panel = Panel(
            content,
            title="[green]Installation Complete![/green]",
            border_style="green",
        )
        self.console.print(panel)
