"""Slash command overlay widget."""

from __future__ import annotations

import importlib
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from cleveragents.tui.slash_catalog import SlashCommandSpec


def _load_static_base() -> type[Any]:
    try:
        return importlib.import_module("textual.widgets").Static
    except Exception:  # pragma: no cover

        class _FallbackStatic:
            def __init__(self, *args: object, **kwargs: object) -> None:
                self._text = ""

            def update(self, text: str) -> None:
                self._text = text

        return _FallbackStatic


_StaticBase = _load_static_base()

_COMMAND_COL_WIDTH = 28  # characters reserved for the command name column


class SlashCommandOverlay(_StaticBase):
    """Renderable list of slash command candidates with keyboard navigation."""

    def __init__(self, *args: object, **kwargs: object) -> None:
        super().__init__(*args, **kwargs)
        self.selected_index: int = 0
        self._commands: list[SlashCommandSpec] = []
        self._visible = False
        self._text = ""

    @property
    def visible(self) -> bool:
        """Return whether the overlay is currently visible."""

        return self._visible

    def hide(self) -> None:
        """Hide the overlay and clear its content."""

        self._visible = False
        self._text = ""
        self._commands = []
        self.selected_index = 0
        self.update("")

    def set_commands(self, query: str, commands: list[SlashCommandSpec]) -> None:
        if not query:
            self.hide()
            return

        filtered = [item for item in commands if item.command.startswith(query)]
        self._commands = filtered
        self.selected_index = 0
        lines = [f"/{query}"]
        for spec in filtered[:12]:
            name_col = f"  /{spec.command}"
            padding = max(1, _COMMAND_COL_WIDTH - len(name_col))
            lines.append(f"{name_col}{' ' * padding}{spec.description}")
        if len(lines) == 1:
            lines.append("  (no commands)")

        self._visible = True
        self._text = "\n".join(lines)
        self.update(self._text)

    def navigate_up(self) -> None:
        """Move selection up by one, clamped to zero."""
        if self.selected_index > 0:
            self.selected_index -= 1

    def navigate_down(self) -> None:
        """Move selection down by one, clamped to last command."""
        max_index = len(self._commands) - 1
        if self.selected_index < max_index:
            self.selected_index += 1

    def select_current(self) -> SlashCommandSpec | None:
        """Return the currently selected SlashCommandSpec, or None if empty."""
        if not self._commands:
            return None
        return self._commands[self.selected_index]

    def dismiss(self) -> None:
        """Dismiss/hide the overlay (Escape key action)."""
        self.hide()
