"""Context-sensitive help panel overlay for the TUI."""

from __future__ import annotations

import importlib
from typing import Any


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()

_GLOBAL_ITEMS = (
    ("ctrl+q", "Quit TUI immediately"),
    ("F1", "Toggle help panel"),
    ("escape", "Close current overlay / return to prompt"),
)

_CONTEXT_ITEMS: dict[str, tuple[tuple[str, str], ...]] = {
    "Main Screen": (
        ("enter", "Submit prompt"),
        ("ctrl+t", "Cycle to next argument preset"),
        ("@", "Open Reference Picker overlay"),
        ("/", "Open Slash Command overlay"),
        ("! / $", "Activate shell mode"),
    ),
    "Slash Commands": (
        ("/", "Show slash command candidates"),
        ("enter", "Submit slash command"),
        ("escape", "Dismiss overlay and return to prompt"),
    ),
    "Reference Picker": (
        ("@", "Search reference candidates"),
        ("enter", "Submit prompt with references"),
        ("escape", "Dismiss overlay and return to prompt"),
    ),
    "Shell Mode": (
        ("enter", "Run shell command"),
        ("tab", "Tab-complete file or directory path"),
        ("backspace", "Exit shell mode at position 0"),
    ),
}


def resolve_help_context(prompt_text: str) -> str:
    """Resolve the help context from the current prompt text."""

    stripped = prompt_text.lstrip()
    if stripped.startswith("/"):
        return "Slash Commands"
    if stripped.startswith(("!", "$")):
        return "Shell Mode"
    if "@" in prompt_text:
        return "Reference Picker"
    return "Main Screen"


def render_help_panel(context_name: str) -> str:
    """Render help content for the requested context."""

    items = _CONTEXT_ITEMS.get(context_name, _CONTEXT_ITEMS["Main Screen"])
    lines = [f"Help: {context_name}", "", "Global"]
    for key, description in _GLOBAL_ITEMS:
        lines.append(f"  {key:<10} {description}")
    lines.append("")
    lines.append(context_name)
    for key, description in items:
        lines.append(f"  {key:<10} {description}")
    return "\n".join(lines)


class HelpPanelOverlay(_StaticBase):
    """Simple static overlay that toggles contextual help text."""

    def __init__(self, *args: object, **kwargs: object) -> None:
        super().__init__(*args, **kwargs)
        self._context_name = ""
        self._visible = False
        self._text = ""

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

        return self._visible

    @property
    def context_name(self) -> str:
        """Return the currently rendered help context name."""

        return self._context_name

    def show_context(self, context_name: str) -> None:
        """Show help content for a specific context."""

        self._context_name = context_name
        self._visible = True
        self._text = render_help_panel(context_name)
        self.update(self._text)

    def hide(self) -> None:
        """Hide the help panel and clear its text."""

        self._context_name = ""
        self._visible = False
        self._text = ""
        self.update("")

    def toggle(self, context_name: str) -> bool:
        """Toggle the panel for the given context.

        Returns ``True`` when the panel ends visible and ``False`` when hidden.
        """

        if self._visible and self._context_name == context_name:
            self.hide()
            return False
        self.show_context(context_name)
        return True
