"""Keybinding help overlay for the ALiCE TUI."""

from __future__ import annotations

from typing import TYPE_CHECKING

from textual.binding import Binding
from textual.containers import Vertical, VerticalScroll
from textual.screen import ModalScreen
from textual.widgets import Static

if TYPE_CHECKING:
    from textual.app import ComposeResult


def _collect_bindings(app, screen) -> list[tuple[str, str]]:  # noqa: ANN001
    """Collect keybindings from the app and the active screen.

    Returns a deduplicated list of ``(key, description)`` tuples.
    App-level bindings come first, then screen-level bindings.
    Bindings with empty descriptions are excluded.
    """
    seen: set[str] = set()
    result: list[tuple[str, str]] = []

    for source in (app, screen):
        bindings = getattr(source, "BINDINGS", [])
        for entry in bindings:
            if isinstance(entry, Binding):
                key = entry.key
                description = entry.description
            elif isinstance(entry, tuple):
                # Textual also accepts (key, action, description) tuples
                key = entry[0]
                description = entry[2] if len(entry) > 2 else ""
            else:
                continue

            if key not in seen and description:
                seen.add(key)
                result.append((key, description))

    return result


class HelpOverlay(ModalScreen[None]):
    """Shows all keybindings for the current screen."""

    BINDINGS = [
        Binding("question_mark", "dismiss", "Close", show=False),
        Binding("escape", "dismiss", "Close", show=False),
    ]

    DEFAULT_CSS = """
    HelpOverlay {
        align: center middle;
    }

    #help-dialog {
        width: 60;
        height: auto;
        max-height: 80%;
        background: #0A1628;
        border: tall #1A3A5C;
        padding: 1 2;
    }

    #help-title {
        text-align: center;
        color: #FFD866;
        text-style: bold;
        width: 100%;
        padding-bottom: 1;
        background: transparent;
    }

    #help-scroll {
        height: auto;
        max-height: 20;
        background: #0A1628;
    }

    .help-row {
        width: 100%;
        height: 1;
        background: #0A1628;
    }

    .help-key {
        width: 16;
        color: #FFD866;
        text-style: bold;
        background: transparent;
    }

    .help-desc {
        width: 1fr;
        color: #FFB000;
        background: transparent;
    }

    #help-hint {
        text-align: center;
        color: #805800;
        width: 100%;
        padding-top: 1;
        background: transparent;
    }
    """

    def compose(self) -> ComposeResult:
        # Collect bindings from the screen underneath this modal
        screens = self.app.screen_stack
        # The active screen is the one below this overlay
        active_screen = screens[-2] if len(screens) >= 2 else self.app.screen
        bindings = _collect_bindings(self.app, active_screen)

        with Vertical(id="help-dialog"):
            yield Static("⌨  Keyboard Shortcuts", id="help-title")
            with VerticalScroll(id="help-scroll"):
                for key, description in bindings:
                    yield _HelpRow(key, description)
            yield Static("Press ? or Esc to close", id="help-hint")

    def action_dismiss(self) -> None:
        """Close the help overlay."""
        self.app.pop_screen()


class _HelpRow(Static):
    """Single row in the help table: key → description."""

    DEFAULT_CLASSES = "help-row"

    def __init__(self, key: str, description: str) -> None:
        super().__init__()
        self._key = key
        self._description = description

    def render(self) -> str:
        # Format the key nicely — replace underscores, capitalize
        display_key = self._key.replace("_", " ")
        return f"[#FFD866 bold]{display_key:<14}[/]  [#FFB000]{self._description}[/]"
