"""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."""

    def set_commands(self, query: str, commands: list[SlashCommandSpec]) -> None:
        filtered = (
            [item for item in commands if item.command.startswith(query)]
            if query
            else list(commands)
        )
        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.update("\n".join(lines))
