class KeyMap:
    """Declarative key-to-action mapping with optional focus scoping.

    Usage::

        km = KeyMap({Keys.ESC: self.go_back})
        km.when("listing", {Keys.ENTER: self.select_item})
        km.dispatch(event.key, focus=self.focus)
    """

    def __init__(self, bindings=None):
        self._global = dict(bindings or {})
        self._scoped = {}  # {focus_name: {key: action}}

    def bind(self, key, action):
        """Add a global key binding."""
        self._global[key] = action

    def unbind(self, key):
        """Remove a global key binding."""
        self._global.pop(key, None)

    def when(self, focus, bindings):
        """Add focus-scoped bindings.

        Parameters
        ----------
        focus : str
            The focus context name these bindings apply to.
        bindings : dict
            Mapping of key code to callable action.
        """
        scope = self._scoped.setdefault(focus, {})
        scope.update(bindings)

    def dispatch(self, key, focus=None):
        """Look up and call the action for *key*.

        Focus-scoped bindings are checked first, then global bindings.
        Returns True if an action was found and called, False otherwise.
        """
        if focus and focus in self._scoped:
            action = self._scoped[focus].get(key)
            if action is not None:
                action()
                return True
        action = self._global.get(key)
        if action is not None:
            action()
            return True
        return False
