#!/bin/bash

# omarchy:summary=Control the Omarchy menu (toggle / summon / close / refresh)
# omarchy:args=[toggle|summon|close|refresh|ping] [route]
# omarchy:examples=omarchy menu | omarchy menu toggle system | omarchy menu summon style.theme | omarchy menu refresh

# Thin wrapper around the standard plugin IPC surface. The menu is the
# first-party `omarchy.menu` plugin; routes are passed as JSON payload.

set -euo pipefail

verb="${1-toggle}"
route="${2-root}"

menu_payload() {
  perl -MEncode=decode -MJSON::PP=encode_json -e 'print encode_json({ menu => decode("UTF-8", $ARGV[0]) })' "$1"
}

case "$verb" in
  toggle)
    exec omarchy-shell shell toggle omarchy.menu "$(menu_payload "$route")"
    ;;
  summon)
    exec omarchy-shell shell summon omarchy.menu "$(menu_payload "$route")"
    ;;
  close)
    exec omarchy-shell shell hide omarchy.menu
    ;;
  refresh | ping)
    exec omarchy-shell shell call omarchy.menu "$verb" "{}"
    ;;
  -h | --help | help)
    cat <<USAGE
Usage: omarchy menu [verb] [route]

Verbs:
  toggle [route]   Open the menu at <route>, or close it if already open. Default verb.
  summon [route]   Always open the menu (no close-if-visible toggle).
  close            Close the menu if it is visible.
  refresh          Re-parse the menu JSONC files.
  ping             Health check.

Route is an item id (e.g. setup.power) or alias (e.g. power). Defaults to
"root", which opens the top-level menu.
USAGE
    exit 0
    ;;
  *)
    echo "omarchy-menu: unknown verb '$verb'. Try 'omarchy menu --help'." >&2
    exit 2
    ;;
esac
