"""Leader key handling and binding registry."""

import time
from muva.config import LEADER_KEY, LEADER_TIMEOUT_MS


class LeaderKeyHandler:
    """Intercepts leader key sequences before passing to active view."""

    def __init__(self):
        self.leader_pressed = False
        self.leader_time = 0
        self.bindings = {}  # key -> callback_name

        # Default leader bindings (lowercase only)
        self.bindings[ord("t")] = "toggle_terminal"
        self.bindings[ord("d")] = "close_pane"
        self.bindings[ord("l")] = "toggle_root_lock"
        self.bindings[ord("n")] = "new_terminal"
        self.bindings[ord("e")] = "jump_explorer"
        self.bindings[ord("r")] = "run_python"
        for i in range(1, 10):
            self.bindings[ord(str(i))] = f"switch_tab:{i}"

    def handle_key(self, key):
        """Process a key. Returns (action_string, consumed).

        If consumed is True, the key was handled by leader logic.
        action_string may be None (leader pressed, waiting for next key)
        or an action name.
        """
        now = time.time()

        if self.leader_pressed:
            self.leader_pressed = False
            elapsed = (now - self.leader_time) * 1000
            if elapsed < LEADER_TIMEOUT_MS:
                action = self.bindings.get(key)
                if action:
                    return action, True
                # Valid second key but not a binding: replay leader + this key
                return "replay_leader", False
            # Timed out: replay leader as a normal key
            return "replay_leader", False

        if key == LEADER_KEY:
            self.leader_pressed = True
            self.leader_time = now
            return None, True

        return None, False
