#!/usr/bin/env python3
# summary: Inspect or change keyboard shortcuts.
"""starchaser shortcuts: keyboard-shortcut helpers for Settings > Shortcuts.

  starchaser shortcuts capture-start       pause Hyprland's own shortcuts so Settings can hear a new combination,
                                           even one already in use (an almost empty submap, so keys reach the
                                           focused window); they come back by themselves after 120 seconds,
                                           so a closed or crashed Settings can't leave the keyboard without them
  starchaser shortcuts capture-renew       give an active capture another 120 seconds
  starchaser shortcuts capture-stop        bring them back now
  starchaser shortcuts profile get         the shortcut profile chosen (starchaser, gnome, kde, xfce, macos, vim, emacs);
                                           profile list marks the one whose keys are in use
  starchaser shortcuts profile list [--json]   every profile, the one in use marked
  starchaser shortcuts profile check ID    check that a shipped profile is installed (read-only)
  starchaser shortcuts profile set ID      switch to profile ID: your changes for the profile you leave are kept for
                                           when you come back, and the ones you made in ID (if any) come back. The
                                           Emacs/Readline profile also turns on Emacs editing keys in text boxes
                                           (GTK 3 apps); leaving it turns them off
  starchaser shortcuts profile preview ID  what switching to ID would change, as JSON
  starchaser shortcuts profile reset       clear your own changes for the profile in use
  starchaser shortcuts keys [--json]       every action and the keys in use for it now (profile and your own
                                           changes included), grouped like the Super+K sheet; for Ask and scripts
  starchaser shortcuts run "Apps: Music"   run a desktop action from the shortcut list
  starchaser shortcuts key "Apps: Music"   that action's key, the way people read it (here: Super + M); the
                                           argument is an action name from the keys list above, and the profile
                                           and your own changes are taken into account. Prints nothing (exit 1)
                                           when the action has no key; an unknown action name says so on stderr
                                           (exit 2). For on-screen text that names a key.
"""

import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_desktop_copy as desktop_copy
from starchaser_cli import command_usage_error, takes_nothing_after, usage_error
from starchaser_hardware_keys import hardware_binds
from starchaser_system_defaults import profile_files

HOME = Path.home()
HYPR = HOME / ".config/hypr"
ACTIVE_FILE = HYPR / "shortcut-profile"
OVERRIDES_LUA = HYPR / "shortcuts.lua"
OVERRIDES_JSON = HOME / ".config/starchaser/shortcuts.json"
SAVED = HOME / ".config/starchaser/shortcut-profiles"
EXPORT = Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") / "starchaser-shortcuts.json"
ORDER = ["starchaser", "gnome", "kde", "xfce", "macos", "windows", "vim", "emacs"]
SUBMAP = "starchaser-capture"
ID_RE = re.compile(r"^[A-Za-z0-9_-]+$")


def usage(out=sys.stdout) -> None:
    out.write(__doc__.lstrip())


def hyprctl(*args: str) -> str:
    try:
        return subprocess.run(["hyprctl", *args], capture_output=True, text=True, timeout=10).stdout
    except (OSError, subprocess.TimeoutExpired):
        return ""


# ---------------------------------------------------------------- capture (Settings listening for a new key)

CAPTURE_FILE = Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") / "starchaser-capture"
CAPTURE_SECONDS = 120


def capture_submap_defined() -> bool:
    try:
        binds = json.loads(hyprctl("-j", "binds") or "[]")
    except (ValueError, RecursionError):
        return False
    return isinstance(binds, list) and any(isinstance(b, dict) and b.get("submap") == SUBMAP for b in binds)


def capture_start() -> None:
    # Each capture gets its own token on file. The 120 s safety timer only ends the capture whose token is still
    # there, so an earlier capture's timer (after Esc and a new pencil) can't cut a later capture short.
    token = f"{os.getpid()}-{time.time_ns()}"
    try:
        CAPTURE_FILE.write_text(token + "\n")
    except OSError:
        token = ""
    # a submap needs one bind to exist: a combination nobody presses, which also ends it. Hyprland runs only the
    # submap's own binds while it's on, so the volume and brightness keys get theirs here too (the same commands as
    # hyprland.lua). The lid and the power button are not repeated here: hyprland.lua binds them with
    # submap_universal, which already covers this submap, and a second copy could run "lid close" twice.
    # Super+L is left out on purpose: while listening, it is a key someone may be giving to an action.
    binds = hardware_binds()
    # Define once per Hyprland start: each definition adds copies of the binds, so two Mute binds undo each other.
    if not capture_submap_defined():
        hyprctl("eval", f'hl.define_submap("{SUBMAP}", function() hl.bind("SUPER + CTRL + ALT + SHIFT + F24", hl.dsp.submap("reset")) {binds} end)')
    hyprctl("eval", f'hl.dispatch(hl.dsp.submap("{SUBMAP}"))')
    arm_capture_watchdog(token)


def arm_capture_watchdog(token: str) -> None:
    f = shlex.quote(str(CAPTURE_FILE))
    check = f'[ "$(cat {f} 2>/dev/null)" = {shlex.quote(token)} ] && ' if token else ""
    subprocess.Popen(["sh", "-c", f"sleep {CAPTURE_SECONDS}; {check}[ \"$(hyprctl submap)\" = {SUBMAP} ] && "
                      f"hyprctl eval 'hl.dispatch(hl.dsp.submap(\"reset\"))'; {check}rm -f {f}"],
                     stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)


def capture_renew() -> None:
    if hyprctl("submap").strip() != SUBMAP:
        return
    token = f"{os.getpid()}-{time.time_ns()}"
    try:
        CAPTURE_FILE.write_text(token + "\n")
    except OSError:
        return
    arm_capture_watchdog(token)


def capture_stop() -> None:
    if hyprctl("submap").strip() == SUBMAP:
        hyprctl("eval", 'hl.dispatch(hl.dsp.submap("reset"))')
    try:
        CAPTURE_FILE.unlink()
    except OSError:
        pass


# ---------------------------------------------------------------- profiles

def active() -> str:
    try:
        line = ACTIVE_FILE.read_text().strip().splitlines()[0].strip()
    except (OSError, IndexError):
        return "starchaser"
    return line if ID_RE.match(line) else "starchaser"


def applied() -> str:
    """The profile whose keys are really in use. hyprland.lua falls back to the Starchaser keys when the chosen
    profile's file can't be loaded, and says so in its export (only trusted when it was written for this choice)."""
    cur, ex = active(), export()
    a = ex.get("applied")
    return a if ex.get("active") == cur and isinstance(a, str) and ID_RE.match(a) else cur


def export() -> dict:
    """What hyprland.lua wrote on its last load: every profile's keys and the config files' own keys."""
    try:
        d = json.loads(EXPORT.read_text())
        return d if isinstance(d, dict) else {}
    except (OSError, ValueError):
        return {}


def lua_field(text: str, name: str) -> str:
    m = re.search(rf'(?m)^\s*{name}\s*=\s*"((?:[^"\\]|\\.)*)"', text)
    return m.group(1).replace('\\"', '"') if m else ""


def profile_file(pid: str) -> Path:
    """This account's own copy of shortcut profile pid, else Starchaser's (neither: a path that doesn't exist)."""
    return profile_files().get(pid) or HYPR / "profiles" / f"{pid}.lua"


def profiles() -> list:
    """[{id, name, about, empty}] in Settings' order, then any other profile file found."""
    ex = export().get("profiles") or {}
    files = profile_files()
    ids = [i for i in ORDER if i in files or i in ex]
    ids += sorted(i for i in files if i not in ids and ID_RE.match(i))
    out = []
    for i in ids:
        p = ex.get(i)
        if isinstance(p, dict):
            name, about, empty = p.get("name") or i, p.get("about") or "", not p.get("keys")
        else:
            # Hyprland hasn't loaded it yet (a profile file added since): the plain fields straight from the file
            try:
                text = files[i].read_text()
            except OSError:
                continue
            name, about = lua_field(text, "name") or i, lua_field(text, "about")
            empty = not re.search(r'\[\s*"', text.split("keys", 1)[-1]) if "keys" in text else True
        out.append({"id": i, "name": name, "about": about, "empty": empty and i != "starchaser"})
    return out


def as_list(v) -> list:
    if isinstance(v, list):
        return v
    if isinstance(v, dict):          # Lua's empty table comes out as {}
        return []
    return [v]


def effective(pid: str, mine: dict) -> dict:
    """description -> keys (or "off") for profile pid with the person's own changes `mine` on top, the way
    hyprland.lua layers them."""
    ex = export()
    profs = ex.get("profiles") or {}
    star = (profs.get("starchaser") or {}).get("keys") or {}
    prof = (profs.get(pid) or {}).get("keys") or {}
    code = ex.get("code") or {}
    hw = set(ex.get("hardware") or [])
    out = {}
    for d in ex.get("codeOrder") or list(code):
        if d in hw:
            continue
        v = prof.get(d) if isinstance(prof, dict) else None
        if v is None:
            v = star.get(d) if isinstance(star, dict) else None
        if v is None:
            v = code.get(d, "")
        for n, k in enumerate(as_list(v)):
            dn = d if n == 0 else f"{d} (key {n + 1})"
            out[dn] = mine.get(dn, k)
    return out


def read_mine(path: Path) -> dict:
    """The person's own changes from a Settings shortcuts.json: description -> keys."""
    try:
        st = json.loads(path.read_text())
    except (OSError, ValueError):
        return {}
    return {d: e["keys"] for d, e in st.items() if isinstance(e, dict) and isinstance(e.get("keys"), str)} if isinstance(st, dict) else {}


def norm(k: str) -> str:
    return re.sub(r"\s", "", str(k or "")).upper()


def preview(pid: str) -> dict:
    ex = export()
    names = {p["id"]: p for p in profiles()}
    if pid not in names:
        return {"error": f"There is no shortcut profile called {pid}."}
    cur = active()
    info = {"id": pid, "name": names[pid]["name"], "about": names[pid]["about"], "empty": names[pid]["empty"],
            "active": cur, "changes": [], "mine": 0}
    if not ex:
        info["error"] = "The preview isn't available until the desktop has loaded its shortcuts once."
        return info
    now_mine = read_mine(OVERRIDES_JSON)
    then_mine = now_mine if pid == cur else read_mine(SAVED / f"{pid}.json")
    info["mine"] = len(then_mine)
    now, then = by_action(effective(cur, now_mine)), by_action(effective(pid, then_mine))
    # one change per action, comparing the SETS of keys: a key the new profile still has is not a change, wherever it
    # sits in the action's list (pairing the nth key with the nth key showed Alt+F2 as "-> Off" for a profile that
    # keeps Alt+F2). Editing still works key by key ("(key 2)" slots); only the preview groups them.
    for d in list(now) + [d for d in then if d not in now]:
        a, b = now.get(d, []), then.get(d, [])
        na, nb = {norm(k) for k in a}, {norm(k) for k in b}
        if na == nb:
            continue
        info["changes"].append({"desc": d, "from": a, "to": b,
                                "removed": [k for k in a if norm(k) not in nb],
                                "added": [k for k in b if norm(k) not in na]})
    return info


def by_action(eff: dict) -> dict:
    """effective()'s "desc" / "desc (key N)" slots -> desc: the keys that work (not off), in slot order, once each."""
    out: dict = {}
    for dn, k in eff.items():
        m = re.fullmatch(r"(.*) \(key \d+\)", dn)
        d = m.group(1) if m else dn
        keys = out.setdefault(d, [])
        if k and str(k).strip().lower() != "off" and norm(k) not in {norm(x) for x in keys}:
            keys.append(k)
    return out


PRETTY = {"SUPER": "Super", "CTRL": "Ctrl", "CONTROL": "Ctrl", "ALT": "Alt", "SHIFT": "Shift", "RETURN": "Enter",
          "SPACE": "Space", "ESCAPE": "Esc", "TAB": "Tab", "PRINT": "Print", "PRIOR": "Page Up", "NEXT": "Page Down",
          "HOME": "Home", "END": "End", "DELETE": "Delete", "INSERT": "Insert", "BACKSPACE": "Backspace",
          "SLASH": "/", "BACKSLASH": "\\", "COMMA": ",", "PERIOD": ".", "SEMICOLON": ";", "APOSTROPHE": "'",
          "BRACKETLEFT": "[", "BRACKETRIGHT": "]", "MINUS": "-", "EQUAL": "=", "GRAVE": "`",
          "LEFT": "Left", "RIGHT": "Right", "UP": "Up", "DOWN": "Down",
          "MOUSE:272": "left mouse button", "MOUSE:273": "right mouse button", "MOUSE:274": "middle mouse button",
          "MOUSE_DOWN": "scroll down", "MOUSE_UP": "scroll up",
          "XF86AUDIORAISEVOLUME": "Volume up key", "XF86AUDIOLOWERVOLUME": "Volume down key", "XF86AUDIOMUTE": "Mute key",
          "XF86AUDIOMICMUTE": "Mic mute key", "XF86AUDIONEXT": "Next track key", "XF86AUDIOPREV": "Previous track key",
          "XF86AUDIOPLAY": "Play key", "XF86AUDIOPAUSE": "Pause key", "XF86MONBRIGHTNESSUP": "Brightness up key",
          "XF86MONBRIGHTNESSDOWN": "Brightness down key", "XF86POWEROFF": "Power button"}


def pretty(combo: str) -> str:
    """ "SUPER + SHIFT + M" -> "Super + Shift + M"; "SUPER + Super_L" -> "Super (tap it alone)"."""
    parts = [p.strip() for p in str(combo).split("+") if p.strip()]
    if parts and re.fullmatch(r"(?i)(super|alt|control|shift)_[lr]", parts[-1]):
        m = parts[-1].split("_")[0].lower()
        return {"control": "Ctrl"}.get(m, m.capitalize()) + " (tap it alone)"
    return " + ".join(PRETTY.get(p.upper(), p.upper() if len(p) == 1 else p) for p in parts)


def key_for(desc: str) -> str:
    """The key in use for an action (its first key that isn't turned off: with the first one off, a profile's
    second key still works), pretty, or "" when it has none."""
    eff = effective(applied(), read_mine(OVERRIDES_JSON))
    n = 1
    while True:
        dn = desc if n == 1 else f"{desc} (key {n})"
        if dn not in eff:
            return ""
        k = eff[dn]
        if k and str(k).lower() != "off":
            return pretty(k)
        n += 1


def all_keys() -> list:
    """Every action with a key in use now: [(action, [keys...])], in the order the shortcut list keeps (the code's
    order), each action's numbered extra keys folded into it. Mouse buttons and the hardware keys are included;
    turned-off keys are not."""
    eff = effective(applied(), read_mine(OVERRIDES_JSON))
    ex = export()
    order = list(ex.get("codeOrder") or []) + [d for d in eff if re.sub(r" \(key \d+\)$", "", d) not in (ex.get("codeOrder") or [])]
    out, seen = [], set()
    for d in order:
        base = re.sub(r" \(key \d+\)$", "", d)
        if base in seen:
            continue
        seen.add(base)
        keys, n = [], 1
        while True:
            dn = base if n == 1 else f"{base} (key {n})"
            if dn not in eff:
                break
            k = eff[dn]
            if k and str(k).lower() != "off":
                keys.append(pretty(k))
            n += 1
        if keys:
            out.append((base, keys))
    return out


def move_in(src: Path, dst: Path) -> None:
    """dst becomes a copy of src, or goes away when there is no src."""
    dst.parent.mkdir(parents=True, exist_ok=True)
    if src.exists():
        tmp = dst.with_name(dst.name + ".tmp")
        shutil.copyfile(src, tmp)
        os.replace(tmp, dst)
    else:
        dst.unlink(missing_ok=True)


# ---------------------------------------------------------------- Readline keys in text boxes (Emacs/Readline only)

GTK3_INI = HOME / ".config/gtk-3.0/settings.ini"
TEXT_KEYS_MARK = SAVED / "text-keys-on"      # we turned them on; holds the key theme to put back when switching away


def ini_set(path: Path, section: str, values: dict) -> None:
    """Set keys in one [section] of an ini file, keeping every other line as it is (None removes a key)."""
    if path.is_symlink():
        path = path.resolve()
    old = path.read_text(errors="replace") if path.exists() else ""
    lines, out, todo, inside, done = old.splitlines(), [], dict(values), False, False
    for ln in lines:
        st = ln.strip()
        if st.startswith("["):
            if inside and not done:
                while out and not out[-1].strip():
                    out.pop()
                out += [f"{k}={v}" for k, v in todo.items() if v is not None] + [""]
                done = True
            inside = st == f"[{section}]"
        elif inside and "=" in ln and ln.split("=", 1)[0].strip() in todo:
            continue                             # replaced (or removed) below
        out.append(ln)
    if not done:
        if not inside:
            if any(v is not None for v in todo.values()):
                out += ([""] if out and out[-1].strip() else []) + [f"[{section}]"]
        while inside and out and not out[-1].strip():
            out.pop()
        out += [f"{k}={v}" for k, v in todo.items() if v is not None]
    text = "\n".join(out).rstrip("\n") + "\n" if out else ""
    if text != old:
        path.parent.mkdir(parents=True, exist_ok=True)
        tmp = path.with_name(path.name + ".tmp")
        tmp.write_text(text)
        os.replace(tmp, path)


def text_keys(pid: str) -> str:
    """The text-box editing keys profile pid asks for: "emacs" or "" (the usual keys)."""
    try:
        return lua_field(profile_file(pid).read_text(), "text_keys")
    except OSError:
        return ""


def gsettings_key_theme(theme: str = "") -> str:
    """Read the GTK key theme from gsettings, or set it when theme is given. "" when gsettings isn't there."""
    cmd = ["gsettings", "set" if theme else "get", "org.gnome.desktop.interface", "gtk-key-theme"] + ([theme] if theme else [])
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
    except (OSError, subprocess.TimeoutExpired):
        return ""
    return r.stdout.strip().strip("'") if r.returncode == 0 and not theme else ""


def ini_get(path: Path, section: str, name: str):
    """The value of name in [section] of an ini file, or None."""
    try:
        lines = path.read_text(errors="replace").splitlines()
    except OSError:
        return None
    inside, val = False, None
    for ln in lines:
        st = ln.strip()
        if st.startswith("["):
            inside = st == f"[{section}]"
        elif inside and "=" in st and st.split("=", 1)[0].strip() == name:
            val = st.split("=", 1)[1].strip()
    return val


def set_text_keys(emacs: bool) -> None:
    """Readline (Emacs) editing keys in GTK 3 text boxes, or back to what was there before. GTK 4 and Qt have no such
    setting. Turning them on saves the key theme in use (gsettings and settings.ini) in TEXT_KEYS_MARK; turning them
    off puts exactly that back, so a theme set by hand before is not lost."""
    if emacs:
        if not TEXT_KEYS_MARK.exists():                  # first time on: remember what to put back
            before = {"gsettings": gsettings_key_theme() or "Default",
                      "ini": ini_get(GTK3_INI, "Settings", "gtk-key-theme-name")}
            SAVED.mkdir(parents=True, exist_ok=True)
            TEXT_KEYS_MARK.write_text(json.dumps(before) + "\n")
        gs, ini = "Emacs", "Emacs"
    else:
        try:
            before = json.loads(TEXT_KEYS_MARK.read_text())
        except (OSError, ValueError):
            before = {}
        if not isinstance(before, dict):
            before = {}
        gs = before.get("gsettings") if isinstance(before.get("gsettings"), str) and before.get("gsettings") else "Default"
        ini = before.get("ini") if isinstance(before.get("ini"), str) else None
    gsettings_key_theme(gs)
    try:
        ini_set(GTK3_INI, "Settings", {"gtk-key-theme-name": ini})
    except OSError as e:
        print(f"starchaser shortcuts: couldn't update {GTK3_INI}: {e}", file=sys.stderr)
    if not emacs:
        TEXT_KEYS_MARK.unlink(missing_ok=True)


def set_profile(pid: str) -> int:
    if not ID_RE.match(pid) or not profile_files().get(pid):
        print(f"starchaser shortcuts: there is no shortcut profile called {pid}", file=sys.stderr)
        return 2
    desktop_copy.save("shortcuts")       # Settings > Recovery > Put my desktop back: the keys from before this
    cur = active()
    if pid != cur:
        # keep this profile's own changes for later, then bring back the ones made in the new profile (none the
        # first time: it starts exactly as designed)
        SAVED.mkdir(parents=True, exist_ok=True)
        move_in(OVERRIDES_LUA, SAVED / f"{cur}.lua")
        move_in(OVERRIDES_JSON, SAVED / f"{cur}.json")
        move_in(SAVED / f"{pid}.lua", OVERRIDES_LUA)
        move_in(SAVED / f"{pid}.json", OVERRIDES_JSON)
    tmp = ACTIVE_FILE.with_name(ACTIVE_FILE.name + ".tmp")
    ACTIVE_FILE.parent.mkdir(parents=True, exist_ok=True)
    tmp.write_text(pid + "\n")
    os.replace(tmp, ACTIVE_FILE)
    hyprctl("reload")
    # the Readline keys in text boxes belong to the Emacs/Readline profile only: on when it asks for them, and off
    # again when leaving it (only if this turned them on, so a key theme set by hand elsewhere is left alone). Read
    # after the reload: a profile file that couldn't be loaded falls back to the Starchaser keys, so it gets none.
    if applied() == pid and text_keys(pid) == "emacs":
        set_text_keys(True)
    elif TEXT_KEYS_MARK.exists():
        set_text_keys(False)
    if sys.stdout.isatty():   # Settings and scripts read the value back and see no change; a terminal is told
        name = lua_field(profile_file(pid).read_text(), "name") or pid
        print(f"Shortcuts now use the {name} profile.")
    return 0


def reset_profile() -> int:
    desktop_copy.save("shortcuts")
    OVERRIDES_LUA.unlink(missing_ok=True)
    OVERRIDES_JSON.unlink(missing_ok=True)
    hyprctl("reload")
    return 0


def profile_usage_error(args, message=None):
    commands = {
        "get": ("profile get", (), ()),
        "list": ("profile list [--json]", (), ()),
        "reset": ("profile reset", (), ()),
        **{name: (f"profile {name} <id>", ("profile ID",), ORDER)
           for name in ("check", "set", "preview")},
    }
    if not args or args[0] not in commands:
        return usage_error("starchaser shortcuts", message or "choose a profile command",
                           "profile <command> [id]", commands)
    return command_usage_error("starchaser shortcuts", args, commands, message)


def profile(args: list) -> int:
    cmd = args[0] if args else ""
    if cmd == "get" and len(args) == 1:
        try:
            pid = ACTIVE_FILE.read_text().strip()
        except FileNotFoundError:
            pid = "starchaser"
        except (OSError, UnicodeError):
            print("The shortcut profile choice could not be read.", file=sys.stderr)
            return 1
        if not ID_RE.fullmatch(pid):
            print("The shortcut profile choice needs attention.", file=sys.stderr)
            return 1
        print(pid)
    elif cmd == "check" and len(args) == 2:
        if args[1] not in ORDER:
            return profile_usage_error(args, f"unknown profile {args[1]!r}")
        try:
            profile_file(args[1]).read_text()
        except (OSError, UnicodeError):
            print("The shortcut profile is not installed here.", file=sys.stderr)
            return 3
        print(json.dumps({"ok": True}))
    elif cmd == "list":
        if args not in (["list"], ["list", "--json"]):
            return profile_usage_error(args, "use profile list with no options or with --json")
        # active: the profile chosen; applied: the one whose keys are in use (Starchaser's when the chosen one
        # couldn't be loaded)
        cur, used = active(), applied()
        ps = [dict(p, active=p["id"] == cur, applied=p["id"] == used) for p in profiles()]
        if "--json" in args:
            print(json.dumps(ps))
        else:
            for p in ps:
                print(f"{'*' if p['applied'] else ' '} {p['id']:<11} {p['name']}{'  (not filled in yet: Starchaser keys)' if p['empty'] else ''}")
            if used != cur:
                name = next((p["name"] for p in ps if p["id"] == cur), cur)
                print(f"The {name} profile couldn't be loaded, so the Starchaser keys are in use.")
    elif cmd == "set" and len(args) == 2 and not args[1].startswith("-"):
        return set_profile(args[1])
    elif cmd == "preview" and len(args) == 2 and not args[1].startswith("-"):
        if args[1] not in ORDER:
            return profile_usage_error(args, f"unknown profile {args[1]!r}")
        result = preview(args[1])
        print(json.dumps(result))
        return 1 if result.get("error") else 0
    elif cmd == "reset" and len(args) == 1:      # `reset --help` deleted the changes instead of explaining
        return reset_profile()
    else:
        return profile_usage_error(args)
    return 0


def shortcuts_usage_error(args):
    commands = {
        **{name: (name, (), ()) for name in ("capture-start", "capture-renew", "capture-stop")},
        "profile": ("profile <command> [id]", ("profile command",), ("get", "list", "check", "set", "preview", "reset")),
        "keys": ("keys [--json]", (), ("--json",)),
        "key": ('key "<action-name>"', ("action name",), ()),
    }
    return command_usage_error("starchaser shortcuts", args, commands)


def run_action(description):
    """Look up the live dispatcher after closing the menu; never simulate key presses."""
    try:
        binds = json.loads(hyprctl("-j", "binds") or "[]")
        bind = next((b for b in binds if b.get("description") == description and not b.get("submap")
                     and not b.get("mouse") and b.get("dispatcher")), None)
        if not bind:
            raise ValueError("This shortcut is no longer available. Reopen the shortcut list.")
        if bind["dispatcher"].startswith(("HL.", "function:")):
            # Lua bind IDs are private to Hyprland. Invoke the action registry, never those IDs as dispatchers.
            quoted = '"' + ''.join('\\%03d' % byte for byte in description.encode('utf-8')) + '"'
            result = hyprctl("eval", "StarchaserActions.run(" + quoted + ")")
        else:
            result = hyprctl("dispatch", bind["dispatcher"], bind.get("arg", ""))
        if result.strip() != "ok":
            raise ValueError("This shortcut couldn't run. " + result.strip())
        return 0
    except (ValueError, TypeError) as error:
        print(str(error), file=sys.stderr)
        return 1


def main() -> int:
    a = sys.argv[1:]
    cmd = a[0] if a else ""
    if "-h" in a or "--help" in a or "help" in a:
        usage()
        return 0
    if cmd == "run" and len(a) == 2:
        return run_action(a[1])
    if cmd in ("capture-start", "capture-renew", "capture-stop") and a[1:]:
        return takes_nothing_after("starchaser shortcuts", cmd, a)
    if cmd == "capture-start":
        capture_start()
    elif cmd == "capture-renew":
        capture_renew()
    elif cmd == "capture-stop":
        capture_stop()
    elif cmd == "profile":
        return profile(a[1:])
    elif cmd == "key" and len(a) != 2:
        return usage_error("starchaser shortcuts", "key needs one action name; use keys to see action names",
                           'key "<action-name>"')
    elif not cmd:
        return shortcuts_usage_error(a)
    elif cmd == "keys" and a[1:] in ([], ["--json"]):
        if not export():
            print("starchaser shortcuts: Couldn't read the desktop's shortcut state. Run this in your desktop session.", file=sys.stderr)
            return 1
        rows = all_keys()
        if a[1:] == ["--json"]:
            print(json.dumps([{"action": d, "keys": k} for d, k in rows]))
        else:
            for d, k in rows:
                print(f"{d}: {' or '.join(k)}")
    elif cmd == "key":
        ex = export()
        known = set(ex.get("codeOrder") or []) | set(ex.get("code") or {}) | set(ex.get("hardware") or [])
        if known and re.sub(r" \(key \d+\)$", "", a[1]) not in known:      # a typo is not the same as "no key yet"
            print(f'starchaser shortcuts: no action called "{a[1]}". Run \'starchaser shortcuts keys\' to see action names.', file=sys.stderr)
            return 2
        k = key_for(a[1])
        if not k:
            return 1
        print(k)
    else:
        return shortcuts_usage_error(a)
    return 0


if __name__ == "__main__":
    sys.exit(main())
