#!/bin/bash

set -o pipefail

OMARCHY_BIN_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
OMARCHY_SYSTEM_BIN_DIR="${OMARCHY_SYSTEM_BIN_DIR-/usr/bin}"
OMARCHY_PACKAGED_BIN_DIR="${OMARCHY_PACKAGED_BIN_DIR:-/usr/share/omarchy/bin}"
OMARCHY_BIN_DIRS=("$OMARCHY_BIN_DIR")
if [[ -n $OMARCHY_SYSTEM_BIN_DIR && -d $OMARCHY_SYSTEM_BIN_DIR && ! $OMARCHY_SYSTEM_BIN_DIR -ef $OMARCHY_BIN_DIR ]] &&
  OMARCHY_SYSTEM_BIN_DIR=$(cd -- "$OMARCHY_SYSTEM_BIN_DIR" 2>/dev/null && pwd); then
  OMARCHY_BIN_DIRS+=("$OMARCHY_SYSTEM_BIN_DIR")
fi
METADATA_SCAN_LIMIT=80

COMMAND_KEYS=()
ROUTE_COLLISIONS=()
declare -A COMMAND_ROUTE
declare -A COMMAND_FALLBACK_ROUTE
declare -A COMMAND_BINARY
declare -A COMMAND_GROUP
declare -A COMMAND_NAME
declare -A COMMAND_SUMMARY
declare -A COMMAND_USAGE
declare -A COMMAND_ARGS
declare -A COMMAND_SUBCOMMANDS
declare -A COMMAND_EXAMPLES
declare -A COMMAND_REQUIRES_SUDO
declare -A COMMAND_HIDDEN
declare -A COMMAND_ALIASES
declare -A COMMAND_HAS_SUMMARY
declare -A COMMAND_METADATA_ERRORS
declare -A ROUTE_TO_KEY
declare -A ROUTE_IS_ALIAS
declare -A BINARY_TO_KEY
declare -A GROUP_DESCRIPTIONS

GROUP_DESCRIPTIONS[agent]="AI coding agents, their usage, and subscription accounts"
GROUP_DESCRIPTIONS[ascii]="Text drawn as ASCII art"
GROUP_DESCRIPTIONS[audio]="Audio input and output controls"
GROUP_DESCRIPTIONS[bar]="Omarchy shell bar layout and settings"
GROUP_DESCRIPTIONS[battery]="Battery status helpers"
GROUP_DESCRIPTIONS[bluetooth]="Bluetooth device controls"
GROUP_DESCRIPTIONS[boot]="Boot loader, boot images and snapshot boot entries"
GROUP_DESCRIPTIONS[branch]="Omarchy git branch management"
GROUP_DESCRIPTIONS[branding]="About and screensaver branding"
GROUP_DESCRIPTIONS[brightness]="Display and keyboard brightness"
GROUP_DESCRIPTIONS[camera]="Webcam relay and image tuning"
GROUP_DESCRIPTIONS[capture]="Screenshots and screen recording"
GROUP_DESCRIPTIONS[channel]="Omarchy release channel management"
GROUP_DESCRIPTIONS[clipboard]="Clipboard helpers"
GROUP_DESCRIPTIONS[cmd]="Command and shortcut helpers"
GROUP_DESCRIPTIONS[config]="System configuration helpers"
GROUP_DESCRIPTIONS[crash]="Crash notification controls"
GROUP_DESCRIPTIONS[finalize]="Finalize user setup"
GROUP_DESCRIPTIONS[default]="Default application selection"
GROUP_DESCRIPTIONS[dev]="Omarchy development tools"
GROUP_DESCRIPTIONS[device]="Hardware controls and settings"
GROUP_DESCRIPTIONS[disk]="Disk performance helpers"
GROUP_DESCRIPTIONS[dictation]="Dictation recording"
GROUP_DESCRIPTIONS[display]="Display and text scaling"
GROUP_DESCRIPTIONS[dns]="DNS resolver configuration"
GROUP_DESCRIPTIONS[dock]="Dock shown on floating workspaces"
GROUP_DESCRIPTIONS[drive]="Drive selection and encryption"
GROUP_DESCRIPTIONS[file]="File selection helpers"
GROUP_DESCRIPTIONS[font]="Font management"
GROUP_DESCRIPTIONS[games]="Game launchers and helpers"
GROUP_DESCRIPTIONS[hibernation]="Hibernation setup and removal"
GROUP_DESCRIPTIONS[hook]="User hook runner"
GROUP_DESCRIPTIONS[hw]="Hardware detection"
GROUP_DESCRIPTIONS[hyprland]="Hyprland window, monitor, and toggle controls"
GROUP_DESCRIPTIONS[icons]="App icon set management"
GROUP_DESCRIPTIONS[install]="Optional software installers"
GROUP_DESCRIPTIONS[installed]="Installed optional service checks"
GROUP_DESCRIPTIONS[launch]="Application launchers"
GROUP_DESCRIPTIONS[kernel]="Default boot kernel selection"
GROUP_DESCRIPTIONS[language]="Display language and system locale"
GROUP_DESCRIPTIONS[menu]="Omarchy menu commands"
GROUP_DESCRIPTIONS[migrate]="Migration runner"
GROUP_DESCRIPTIONS[monitor]="Monitor status helpers"
GROUP_DESCRIPTIONS[network]="Network, Wi-Fi, and Ethernet controls"
GROUP_DESCRIPTIONS[notification]="Notification helpers"
GROUP_DESCRIPTIONS[models]="Open models running on this machine and the tailnet"
GROUP_DESCRIPTIONS[mise]="Mise tool wrappers"
GROUP_DESCRIPTIONS[openclaw]="OpenClaw agent platform setup"
GROUP_DESCRIPTIONS[osd]="On-screen display status helpers"
GROUP_DESCRIPTIONS[pkg]="Package management helpers"
GROUP_DESCRIPTIONS[plugin]="Omarchy shell plugin and bar widget management"
GROUP_DESCRIPTIONS[power]="Power supply detection"
GROUP_DESCRIPTIONS[powerprofiles]="Power profile management"
GROUP_DESCRIPTIONS[refresh]="Reset config to defaults"
GROUP_DESCRIPTIONS[region]="The region this machine was installed for, and how dates, times, numbers and units are written"
GROUP_DESCRIPTIONS[reinstall]="Reinstall and reset workflows"
GROUP_DESCRIPTIONS[reminder]="Desktop notification reminders"
GROUP_DESCRIPTIONS[remove]="Removal workflows"
GROUP_DESCRIPTIONS[restart]="Restart Omarchy components"
GROUP_DESCRIPTIONS[rollcall]="Hardware roll call: what answers, what is there but broken, what is absent"
GROUP_DESCRIPTIONS[setup]="Interactive setup wizards"
GROUP_DESCRIPTIONS[shell]="Omarchy shell IPC helpers"
GROUP_DESCRIPTIONS[snapshot]="System snapshots"
GROUP_DESCRIPTIONS[sudo]="Sudo configuration helpers"
GROUP_DESCRIPTIONS[system]="System status, reboot, shutdown, logout, and lock"
GROUP_DESCRIPTIONS[tailscale]="Tailscale helpers"
GROUP_DESCRIPTIONS[theme]="Theme management"
GROUP_DESCRIPTIONS[toggle]="Toggle Omarchy features"
GROUP_DESCRIPTIONS[transcode]="Image and video transcoding"
GROUP_DESCRIPTIONS[tui]="Terminal UI launchers"
GROUP_DESCRIPTIONS[update]="Omarchy and system updates"
GROUP_DESCRIPTIONS[version]="Version and channel information"
GROUP_DESCRIPTIONS[voxtype]="Voxtype dictation"
GROUP_DESCRIPTIONS[weather]="Weather status"
GROUP_DESCRIPTIONS[webapp]="Web app launchers"
GROUP_DESCRIPTIONS[wifi]="Wi-Fi helpers"
GROUP_DESCRIPTIONS[windows]="Windows VM management"

join_words() {
  local separator="$1"
  shift
  local joined=""

  for word in "$@"; do
    if [[ -z $joined ]]; then
      joined="$word"
    else
      joined+="$separator$word"
    fi
  done

  printf '%s' "$joined"
}

append_pipe_value() {
  local current="$1"
  local addition="$2"

  if [[ -z $current ]]; then
    printf '%s' "$addition"
  else
    printf '%s|%s' "$current" "$addition"
  fi
}

# A route can resolve to a binary before all args are consumed (`update aur` only matches the `update` binary, leaving `aur` and `--help` as leftovers)
# --help must never be lost among those leftovers and get forwarded into the real command, so this checks the whole remainder rather than just the first token.
# A `--` marks everything after it as belonging to the command itself, so scanning stops there.
remaining_has_help_flag() {
  local token=""

  for token in "$@"; do
    [[ $token == "--" ]] && break
    [[ $token == "--help" || $token == "-h" ]] && return 0
  done

  return 1
}

remaining_has_json_flag() {
  local token=""

  for token in "$@"; do
    [[ $token == "--" ]] && break
    [[ $token == "--json" ]] && return 0
  done

  return 1
}

register_route() {
  local route="$1"
  local key="$2"
  local is_alias="${3:-false}"

  [[ -z $route || -z $key ]] && return

  if [[ -n ${ROUTE_TO_KEY[$route]} && ${ROUTE_TO_KEY[$route]} != "$key" ]]; then
    ROUTE_COLLISIONS+=("$route -> ${ROUTE_TO_KEY[$route]} conflicts with $key")
    return
  fi

  ROUTE_TO_KEY["$route"]="$key"
  if [[ $is_alias == "true" ]]; then
    ROUTE_IS_ALIAS["$route"]="true"
  fi
}

store_command_metadata() {
  local file_binary="$1"
  local group="$2"
  local name="$3"
  local name_seen="$4"
  local summary="$5"
  local has_summary="$6"
  local fallback_summary="$7"
  local args="$8"
  local subcommands="$9"
  local examples="${10}"
  local aliases="${11}"
  local requires_sudo="${12}"
  local hidden="${13}"
  local metadata_errors="${14}"

  local stem="${file_binary#omarchy-}"
  local fallback_group="$stem"
  local fallback_name=""
  local fallback_route="omarchy ${stem//-/ }"

  if [[ $stem == *-* ]]; then
    fallback_group="${stem%%-*}"
    fallback_name="${stem#*-}"
    fallback_name="${fallback_name//-/ }"
  fi

  [[ -z $group ]] && group="$fallback_group"
  [[ $name_seen != "true" ]] && name="$fallback_name"
  [[ -z $summary && -n $fallback_summary ]] && summary="$fallback_summary"
  [[ -z $summary ]] && summary="Run the ${stem//-/ } command"
  local route="omarchy $group"
  if [[ -n $name ]]; then
    route+=" $name"
  fi

  # Subcommands stand in for args, as alternatives: `use <id> | reset | ...`
  if [[ -z $args && -n $subcommands ]]; then
    local subcommand_args=""
    local subcommand_summary=""
    while IFS=$'\t' read -r subcommand_args subcommand_summary; do
      args+="${args:+ | }$subcommand_args"
    done <<<"${subcommands%$'\n'}"
  fi

  local usage="$route"
  if [[ -n $args ]]; then
    usage+=" $args"
  fi

  [[ $requires_sudo == "true" ]] || requires_sudo="false"
  [[ $hidden == "true" ]] || hidden="false"

  local key="$file_binary"
  COMMAND_KEYS+=("$key")
  COMMAND_ROUTE["$key"]="$route"
  COMMAND_FALLBACK_ROUTE["$key"]="$fallback_route"
  COMMAND_BINARY["$key"]="$file_binary"
  COMMAND_GROUP["$key"]="$group"
  COMMAND_NAME["$key"]="$name"
  COMMAND_SUMMARY["$key"]="$summary"
  COMMAND_USAGE["$key"]="$usage"
  COMMAND_ARGS["$key"]="$args"
  COMMAND_SUBCOMMANDS["$key"]="${subcommands%$'\n'}"
  COMMAND_EXAMPLES["$key"]="$examples"
  COMMAND_REQUIRES_SUDO["$key"]="$requires_sudo"
  COMMAND_HIDDEN["$key"]="$hidden"
  COMMAND_HAS_SUMMARY["$key"]="$has_summary"
  COMMAND_METADATA_ERRORS["$key"]="$metadata_errors"

  BINARY_TO_KEY["$file_binary"]="$key"
  register_route "$route" "$key"
  register_route "$fallback_route" "$key"

  if [[ -n $aliases ]]; then
    local alias_route=""
    local alias_routes=()
    IFS='|' read -ra alias_routes <<<"$aliases"
    for alias_route in "${alias_routes[@]}"; do
      alias_route="${alias_route# }"
      alias_route="${alias_route% }"
      [[ -z $alias_route || $alias_route == "$route" ]] && continue
      register_route "$alias_route" "$key" true
      if [[ -z ${COMMAND_ALIASES[$key]:-} ]]; then
        COMMAND_ALIASES["$key"]="$alias_route"
      else
        COMMAND_ALIASES["$key"]="${COMMAND_ALIASES[$key]}|$alias_route"
      fi
    done
  fi
}

register_command() {
  local file="$1"
  local file_binary="${file##*/}"
  local group=""
  local name=""
  local summary=""
  local args=""
  local subcommands=""
  local examples=""
  local aliases=""
  local requires_sudo=""
  local hidden=""
  local line=""
  local metadata_key=""
  local metadata_value=""
  local line_count=0
  local name_seen="false"
  local fallback_summary=""
  local has_summary="false"
  local metadata_errors=""

  while IFS= read -r line && (( line_count < METADATA_SCAN_LIMIT )); do
    line_count=$((line_count + 1))

    if (( line_count == 1 )) && [[ $line == "#!"* ]]; then
      continue
    fi

    if [[ $line =~ ^[[:space:]]*$ ]]; then
      continue
    fi

    if [[ ! $line =~ ^[[:space:]]*# ]]; then
      break
    fi

    if [[ $line =~ ^[[:space:]]*#[[:space:]]*omarchy:([[:alnum:]_-]+)=(.*)$ ]]; then
      metadata_key="${BASH_REMATCH[1]}"
      metadata_value="${BASH_REMATCH[2]}"
      metadata_value="${metadata_value%$'\r'}"
      metadata_value="${metadata_value//$'\t'/ }"

      case "$metadata_key" in
      group)
        group="$metadata_value"
        ;;
      name)
        name="$metadata_value"
        name_seen="true"
        ;;
      summary)
        summary="$metadata_value"
        [[ -n $metadata_value ]] && has_summary="true"
        ;;
      args)
        args="$metadata_value"
        ;;
      subcommand)
        if [[ $metadata_value == *" — "* ]]; then
          subcommands+="${metadata_value%% — *}"$'\t'"${metadata_value#* — }"$'\n'
        else
          metadata_errors=$(append_pipe_value "$metadata_errors" "subcommand must be '<args> — <summary>'")
        fi
        ;;
      examples)
        examples="$metadata_value"
        ;;
      alias | aliases)
        aliases="$metadata_value"
        ;;
      requires-sudo)
        requires_sudo="$metadata_value"
        [[ $metadata_value == "true" ]] || metadata_errors=$(append_pipe_value "$metadata_errors" "requires-sudo must be omitted or true")
        ;;
      hidden)
        hidden="$metadata_value"
        [[ $metadata_value == "true" ]] || metadata_errors=$(append_pipe_value "$metadata_errors" "hidden must be omitted or true")
        ;;
      *)
        ;;
      esac
    elif [[ -z $fallback_summary && $line =~ ^[[:space:]]*#[[:space:]]*(.+)$ ]]; then
      fallback_summary="${BASH_REMATCH[1]}"
      fallback_summary="${fallback_summary%$'\r'}"
      fallback_summary="${fallback_summary//$'\t'/ }"

      if [[ -z $fallback_summary || $fallback_summary == omarchy:* ]]; then
        fallback_summary=""
      fi
    fi
  done <"$file"

  store_command_metadata \
    "$file_binary" "$group" "$name" "$name_seen" "$summary" "$has_summary" \
    "$fallback_summary" "$args" "$subcommands" "$examples" "$aliases" \
    "$requires_sudo" "$hidden" "$metadata_errors"
}

# Scan a batch of command headers in one awk pass (~7ms for all ~630 files vs
# ~260ms in pure-Bash read/regex loops). Single-file loads stay in Bash to
# avoid an awk fork.
register_command_files() {
  (( $# > 0 )) || return 0
  if (( $# == 1 )); then
    register_command "$1"
    return 0
  fi

  local key route fallback_route group name summary usage args subcommands_raw
  local examples aliases requires_sudo hidden has_summary metadata_errors
  local subcommands sub_entry alias_route
  local -a alias_routes

  while IFS=$'\x1f' read -r \
    key route fallback_route group name summary usage args subcommands_raw \
    examples aliases requires_sudo hidden has_summary metadata_errors; do
    subcommands=""
    if [[ -n $subcommands_raw ]]; then
      subcommands="${subcommands_raw//$'\x1d'/$'\t'}"
      subcommands="${subcommands//$'\x1e'/$'\n'}"
    fi

    COMMAND_KEYS+=("$key")
    COMMAND_ROUTE["$key"]="$route"
    COMMAND_FALLBACK_ROUTE["$key"]="$fallback_route"
    COMMAND_BINARY["$key"]="$key"
    COMMAND_GROUP["$key"]="$group"
    COMMAND_NAME["$key"]="$name"
    COMMAND_SUMMARY["$key"]="$summary"
    COMMAND_USAGE["$key"]="$usage"
    COMMAND_ARGS["$key"]="$args"
    COMMAND_SUBCOMMANDS["$key"]="$subcommands"
    COMMAND_EXAMPLES["$key"]="$examples"
    COMMAND_REQUIRES_SUDO["$key"]="$requires_sudo"
    COMMAND_HIDDEN["$key"]="$hidden"
    COMMAND_HAS_SUMMARY["$key"]="$has_summary"
    COMMAND_METADATA_ERRORS["$key"]="$metadata_errors"
    BINARY_TO_KEY["$key"]="$key"

    if [[ -n ${ROUTE_TO_KEY[$route]:-} && ${ROUTE_TO_KEY[$route]} != "$key" ]]; then
      ROUTE_COLLISIONS+=("$route -> ${ROUTE_TO_KEY[$route]} conflicts with $key")
    else
      ROUTE_TO_KEY["$route"]="$key"
    fi

    if [[ $fallback_route != "$route" ]]; then
      if [[ -n ${ROUTE_TO_KEY[$fallback_route]:-} && ${ROUTE_TO_KEY[$fallback_route]} != "$key" ]]; then
        ROUTE_COLLISIONS+=("$fallback_route -> ${ROUTE_TO_KEY[$fallback_route]} conflicts with $key")
      else
        ROUTE_TO_KEY["$fallback_route"]="$key"
      fi
    fi

    if [[ -n $aliases ]]; then
      IFS='|' read -ra alias_routes <<<"$aliases"
      for alias_route in "${alias_routes[@]}"; do
        if [[ -n ${ROUTE_TO_KEY[$alias_route]:-} && ${ROUTE_TO_KEY[$alias_route]} != "$key" ]]; then
          ROUTE_COLLISIONS+=("$alias_route -> ${ROUTE_TO_KEY[$alias_route]} conflicts with $key")
        else
          ROUTE_TO_KEY["$alias_route"]="$key"
          ROUTE_IS_ALIAS["$alias_route"]="true"
        fi
      done
      COMMAND_ALIASES["$key"]="$aliases"
    fi
  done < <(
    awk -v limit="$METADATA_SCAN_LIMIT" '
      function append_err(msg) {
        metadata_errors = (metadata_errors == "" ? msg : metadata_errors "|" msg)
      }
      function reset_file(path) {
        file_binary = path
        sub(/^.*\//, "", file_binary)
        group = ""; name = ""; name_seen = 0
        summary = ""; has_summary = "false"; fallback_summary = ""
        args = ""; subcommands = ""; sub_args_joined = ""
        examples = ""; aliases = ""
        requires_sudo = ""; hidden = ""; metadata_errors = ""
      }
      function emit_file(   stem, fallback_group, fallback_name, fallback_route, dash, route, usage, n, i, a, clean_aliases, parts) {
        stem = file_binary
        sub(/^omarchy-/, "", stem)
        fallback_group = stem
        fallback_name = ""
        fallback_route = stem
        gsub(/-/, " ", fallback_route)
        fallback_route = "omarchy " fallback_route

        dash = index(stem, "-")
        if (dash > 0) {
          fallback_group = substr(stem, 1, dash - 1)
          fallback_name = substr(stem, dash + 1)
          gsub(/-/, " ", fallback_name)
        }

        if (group == "") group = fallback_group
        if (!name_seen) name = fallback_name
        if (summary == "" && fallback_summary != "") summary = fallback_summary
        if (summary == "") {
          summary = stem
          gsub(/-/, " ", summary)
          summary = "Run the " summary " command"
        }

        route = "omarchy " group
        if (name != "") route = route " " name

        if (args == "" && sub_args_joined != "") args = sub_args_joined
        usage = (args != "" ? route " " args : route)
        if (requires_sudo != "true") requires_sudo = "false"
        if (hidden != "true") hidden = "false"

        clean_aliases = ""
        if (aliases != "") {
          n = split(aliases, parts, "|")
          for (i = 1; i <= n; i++) {
            a = parts[i]
            sub(/^ /, "", a)
            sub(/ $/, "", a)
            if (a == "" || a == route) continue
            clean_aliases = (clean_aliases == "" ? a : clean_aliases "|" a)
          }
        }

        printf "%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\n", \
          file_binary, route, fallback_route, group, name, summary, usage, args, \
          subcommands, examples, clean_aliases, requires_sudo, hidden, has_summary, metadata_errors
      }
      BEGINFILE {
        reset_file(FILENAME)
        if (ERRNO != "") {
          printf "omarchy: %s: %s\n", FILENAME, ERRNO > "/dev/stderr"
          emit_file()
          nextfile
        }
      }
      ENDFILE { emit_file() }
      FNR > limit { nextfile }
      FNR == 1 && /^#!/ { next }
      /^[[:space:]]*$/ { next }
      !/^[[:space:]]*#/ { nextfile }
      {
        if (match($0, /^[[:space:]]*#[[:space:]]*omarchy:([[:alnum:]_-]+)=(.*)$/, m)) {
          k = m[1]
          v = m[2]
          sub(/\r$/, "", v)
          gsub(/\t/, " ", v)
          if (k == "group") group = v
          else if (k == "name") { name = v; name_seen = 1 }
          else if (k == "summary") { summary = v; if (v != "") has_summary = "true" }
          else if (k == "args") args = v
          else if (k == "subcommand") {
            sep = index(v, " — ")
            if (sep > 0) {
              sa = substr(v, 1, sep - 1)
              ss = substr(v, sep + length(" — "))
              entry = sa "\x1d" ss
              subcommands = (subcommands == "" ? entry : subcommands "\x1e" entry)
              sub_args_joined = (sub_args_joined == "" ? sa : sub_args_joined " | " sa)
            } else {
              append_err("subcommand must be \x27<args> — <summary>\x27")
            }
          }
          else if (k == "examples") examples = v
          else if (k == "alias" || k == "aliases") aliases = v
          else if (k == "requires-sudo") {
            requires_sudo = v
            if (v != "true") append_err("requires-sudo must be omitted or true")
          }
          else if (k == "hidden") {
            hidden = v
            if (v != "true") append_err("hidden must be omitted or true")
          }
        } else if (fallback_summary == "" && match($0, /^[[:space:]]*#[[:space:]]*(.+)$/, m)) {
          v = m[1]
          sub(/\r$/, "", v)
          gsub(/\t/, " ", v)
          if (v != "" && v !~ /^omarchy:/) fallback_summary = v
        }
      }
    ' "$@"
  )
}

reset_commands() {
  COMMAND_KEYS=()
  ROUTE_COLLISIONS=()
  COMMAND_ROUTE=() COMMAND_FALLBACK_ROUTE=() COMMAND_BINARY=() COMMAND_GROUP=() COMMAND_NAME=()
  COMMAND_SUMMARY=() COMMAND_USAGE=() COMMAND_ARGS=() COMMAND_SUBCOMMANDS=() COMMAND_EXAMPLES=() COMMAND_REQUIRES_SUDO=()
  COMMAND_HIDDEN=() COMMAND_ALIASES=() COMMAND_HAS_SUMMARY=() COMMAND_METADATA_ERRORS=()
  ROUTE_TO_KEY=() ROUTE_IS_ALIAS=() BINARY_TO_KEY=()
}

command_file_usable() {
  local dir="$1"
  local file="$2"

  [[ -f $file && -x $file ]] || return 1

  # A dev checkout replaces the runtime commands linked from the packaged tree.
  [[ $dir == "$OMARCHY_BIN_DIR" || ! $OMARCHY_PACKAGED_BIN_DIR/${file##*/} -ef $file ]]
}

resolve_binary_path() {
  local binary="$1"
  local dir=""
  local candidate=""

  for dir in "${OMARCHY_BIN_DIRS[@]}"; do
    candidate="$dir/$binary"
    if command_file_usable "$dir" "$candidate"; then
      RESOLVED_BINARY_PATH="$candidate"
      return 0
    fi
  done

  RESOLVED_BINARY_PATH=""
  return 1
}

collect_command_files() {
  local -n collected_files_ref="$1"
  local prefix="$2"
  local dir=""
  local file=""
  local binary=""
  local -A seen=()

  collected_files_ref=()
  for dir in "${OMARCHY_BIN_DIRS[@]}"; do
    for file in "$dir/$prefix"*; do
      command_file_usable "$dir" "$file" || continue
      binary="${file##*/}"
      [[ -n ${seen[$binary]:-} ]] && continue
      seen["$binary"]=1
      collected_files_ref+=("$file")
    done
  done
}

load_commands() {
  local files=()

  collect_command_files files "omarchy-"
  register_command_files "${files[@]}"
}

# Only a command whose route starts with "omarchy <first>" can resolve a route
# beginning with that word: one in the <first> group by filename or metadata, or
# one with an alias under it. Loading just those resolves aliases and
# metadata-moved routes without reading every header. A superset is harmless,
# and they register in the same order a full load would use.
load_route_candidates() {
  local first="$1"
  local -A seen=()
  local dir=""
  local file=""
  local binary=""
  local grep_files=()
  local files=()

  [[ $first =~ ^[[:alnum:]][[:alnum:]_-]*$ ]] || return 1

  if (( ${#OMARCHY_BIN_DIRS[@]} == 1 )); then
    grep_files=("$OMARCHY_BIN_DIR"/omarchy-*)
  else
    collect_command_files grep_files "omarchy-"
  fi

  for dir in "${OMARCHY_BIN_DIRS[@]}"; do
    for file in "$dir/omarchy-$first"-*; do
      command_file_usable "$dir" "$file" || continue
      binary="${file##*/}"
      [[ -n ${seen[$binary]:-} ]] || seen["$binary"]="$file"
    done
  done
  if (( ${#grep_files[@]} > 0 )); then
    while IFS= read -r file; do
      [[ -f $file && -x $file ]] || continue
      binary="${file##*/}"
      [[ -n ${seen[$binary]:-} ]] || seen["$binary"]="$file"
    done < <(grep -I -l -E -e "omarchy:group=$first([^[:alnum:]_-]|$)" -e "omarchy:alias(es)?=.*omarchy[[:space:]]+$first([[:space:]]|\||$)" -- "${grep_files[@]}" 2>/dev/null)
  fi

  # The full load's own order, so colliding routes register identically.
  # When only one candidate matched, order cannot matter, skipping the scan.
  if (( ${#seen[@]} == 1 )); then
    for file in "${seen[@]}"; do
      files+=("$file")
    done
  elif (( ${#seen[@]} > 1 )); then
    for file in "${grep_files[@]}"; do
      binary="${file##*/}"
      [[ ${seen[$binary]:-} == "$file" ]] || continue
      files+=("$file")
    done
  fi

  register_command_files "${files[@]}"
}

load_command_by_binary() {
  local binary="$1"

  resolve_binary_path "$binary" || return 1
  register_command "$RESOLVED_BINARY_PATH"
}

load_child_commands_by_binary() {
  local binary="$1"
  local files=()

  collect_command_files files "$binary-"
  register_command_files "${files[@]}"
}

group_has_child_commands() {
  local group="$1"
  local dir=""
  local file=""

  for dir in "${OMARCHY_BIN_DIRS[@]}"; do
    for file in "$dir/omarchy-$group"-*; do
      command_file_usable "$dir" "$file" && return 0
    done
  done

  return 1
}

group_has_binary_commands() {
  local group="$1"

  resolve_binary_path "omarchy-$group" && return 0
  group_has_child_commands "$group"
}

command_requires_args() {
  local key="$1"
  local args="${COMMAND_ARGS[$key]}"
  local required="$args"

  while [[ $required =~ ^(.*)\[[^][]*\](.*)$ ]]; do
    required="${BASH_REMATCH[1]}${BASH_REMATCH[2]}"
  done

  required="${required// /}"
  [[ -n $required ]]
}

# A command whose documented arguments are all flags can't take a word, so a
# word after it names something else: `omarchy agent account` is the account
# commands, not an argument to omarchy-agent.
command_takes_only_flags() {
  local key="$1"
  local args="${COMMAND_ARGS[$key]}"
  local token=""
  local tokens=()
  local in_option=false

  [[ -n $args ]] || return 1
  read -ra tokens <<<"$args"
  # An optional flag may name its value, as in [--model <name>]; the value
  # placeholder belongs to the flag and isn't a positional argument.
  for token in "${tokens[@]}"; do
    if [[ $token == -* || $token == "[-"* ]]; then
      if [[ $token == "[-"* && $token != *"]" ]]; then
        in_option=true
      else
        in_option=false
      fi
    elif [[ $in_option == true ]]; then
      if [[ $token == *"]" ]]; then
        in_option=false
      fi
    else
      return 1
    fi
  done
}

load_group_commands() {
  local group="$1"
  local files=()
  local child_files=()

  if resolve_binary_path "omarchy-$group"; then
    files+=("$RESOLVED_BINARY_PATH")
  fi

  collect_command_files child_files "omarchy-$group-"
  files+=("${child_files[@]}")

  register_command_files "${files[@]}"
}

resolve_direct_route() {
  local argc="$1"
  shift
  local args=("$@")
  local prefix_count=0
  local route=""
  local binary=""

  for (( prefix_count = argc; prefix_count >= 1; prefix_count-- )); do
    route="omarchy $(join_words " " "${args[@]:0:prefix_count}")"

    binary="omarchy-$(join_words "-" "${args[@]:0:prefix_count}")"
    if resolve_binary_path "$binary"; then
      DIRECT_RESOLVED_BINARY="$binary"
      DIRECT_RESOLVED_PATH="$RESOLVED_BINARY_PATH"
      DIRECT_RESOLVED_COUNT="$prefix_count"
      DIRECT_RESOLVED_ROUTE="$route"
      return 0
    fi
  done

  return 1
}

sorted_keys() {
  local include_all="$1"
  local key=""

  for key in "${COMMAND_KEYS[@]}"; do
    if [[ $include_all != "true" && ${COMMAND_HIDDEN[$key]} == "true" ]]; then
      continue
    fi
    printf '%s\t%s\n' "${COMMAND_ROUTE[$key]}" "$key"
  done | sort -u | cut -f2-
}

fallback_group_for_key() {
  local key="$1"
  local fallback="${COMMAND_FALLBACK_ROUTE[$key]#omarchy }"

  printf '%s' "${fallback%% *}"
}

command_route_for_group() {
  local key="$1"
  local group="$2"

  if [[ $(fallback_group_for_key "$key") == "$group" && ${COMMAND_GROUP[$key]} != "$group" ]]; then
    printf '%s' "${COMMAND_FALLBACK_ROUTE[$key]}"
  else
    printf '%s' "${COMMAND_ROUTE[$key]}"
  fi
}

# Appends a command's table rows under the given route to the named variable:
# one per declared subcommand, each with its own summary, or a single row with
# the full usage. Appending in place keeps full listings free of a subshell per
# command.
append_command_rows() {
  local -n command_rows_ref="$1"
  local key="$2"
  local route="$3"
  local subcommand_args=""
  local subcommand_summary=""

  if [[ -n ${COMMAND_SUBCOMMANDS[$key]} ]]; then
    while IFS=$'\t' read -r subcommand_args subcommand_summary; do
      command_rows_ref+="$route $subcommand_args"$'\t'"$subcommand_summary"$'\n'
    done <<<"${COMMAND_SUBCOMMANDS[$key]}"
  else
    command_rows_ref+="$route${COMMAND_ARGS[$key]:+ ${COMMAND_ARGS[$key]}}"$'\t'"${COMMAND_SUMMARY[$key]}"$'\n'
  fi
}

sorted_group_keys() {
  local group="$1"
  local include_all="$2"
  local key=""
  local fallback_group=""
  local route=""

  for key in "${COMMAND_KEYS[@]}"; do
    if [[ $include_all != "true" && ${COMMAND_HIDDEN[$key]} == "true" ]]; then
      continue
    fi

    fallback_group=$(fallback_group_for_key "$key")
    if [[ ${COMMAND_GROUP[$key]} != "$group" && $fallback_group != "$group" ]]; then
      continue
    fi

    route=$(command_route_for_group "$key" "$group")
    printf '%s\t%s\n' "$route" "$key"
  done | sort -u | cut -f2-
}

pipe_values_as_lines() {
  local values="$1"
  local value=""
  local items=()

  IFS='|' read -ra items <<<"$values"
  for value in "${items[@]}"; do
    value="${value# }"
    value="${value% }"
    [[ -n $value ]] && printf '%s\n' "$value"
  done
}

examples_as_lines() {
  pipe_values_as_lines "$1"
}

show_group_list() {
  local sorted_group=""

  printf '%s\n' "${!GROUP_DESCRIPTIONS[@]}" | sort | while IFS= read -r sorted_group; do
    [[ -n $sorted_group ]] || continue
    printf '  %-14s %s\n' "$sorted_group" "${GROUP_DESCRIPTIONS[$sorted_group]}"
  done
}

show_main_help() {
  cat <<'EOF'
Omarchy command center

Usage:
  omarchy <command> [args...]
  omarchy commands [--all] [--json] [--check]
  omarchy <group> --help
  omarchy <group> <command> --help

Common commands:
  omarchy update              Update Omarchy and system packages
  omarchy theme list          List available themes
  omarchy theme set <name>    Apply a theme
  omarchy font list           List available fonts
  omarchy screenshot          Take a screenshot
  omarchy-debug               Print debugging information

Groups:
EOF
  show_group_list
  cat <<'EOF'

Discovery:
  omarchy commands            List all commands
  omarchy commands --all      Include commands explicitly marked hidden
  omarchy commands --json     Machine-readable command list
  omarchy commands --check    Validate command metadata and routes
EOF
}

show_commands_help() {
  cat <<'EOF'
Usage:
  omarchy commands [--all] [--json] [--markdown] [--check]

List commands known to the Omarchy command center.

Options:
  --all       Include commands explicitly marked hidden
  --json      Emit machine-readable JSON
  --markdown  Emit a Markdown command table
  --check     Validate command metadata and route collisions
EOF
}

print_command_table() {
  local rows="$1"
  local max_width=0
  local width=0
  local command=""
  local rest=""
  local summary=""

  while IFS=$'\t' read -r command rest; do
    [[ -n $command ]] || continue
    width=${#command}
    (( width > max_width )) && max_width=$width
  done <<<"$rows"

  # Cap the column so a usage longer than 48 characters pushes only its own summary
  # along, rather than padding every row out past the edge of a normal terminal.
  (( max_width > 48 )) && max_width=48

  while IFS=$'\t' read -r command rest; do
    [[ -n $command ]] || continue

    printf '  %-*s  %s\n' "$max_width" "$command" "$rest"
  done <<<"$rows"
}

show_commands() {
  local include_all="$1"
  local key=""
  local route=""
  local rows=""
  local alias_rows=""

  if [[ $include_all == "true" ]]; then
    echo "Armbian commands (all):"
  else
    echo "Armbian commands:"
  fi

  while IFS= read -r key; do
    [[ -n $key ]] || continue
    append_command_rows rows "$key" "${COMMAND_ROUTE[$key]}"
  done < <(sorted_keys "$include_all")

  print_command_table "$rows"

  for route in "${!ROUTE_IS_ALIAS[@]}"; do
    key="${ROUTE_TO_KEY[$route]}"
    if [[ $include_all != "true" && ${COMMAND_HIDDEN[$key]} == "true" ]]; then
      continue
    fi
    alias_rows+="$route"$'\t'"${COMMAND_ROUTE[$key]}"$'\n'
  done

  if [[ -n $alias_rows ]]; then
    echo ""
    echo "Aliases:"
    print_command_table "$(printf '%s' "$alias_rows" | sort)"
  fi
}

markdown_escape() {
  local value="$1"
  value="${value//|/\\|}"
  printf '%s' "$value"
}

show_commands_markdown() {
  local include_all="$1"
  local key=""
  local rows=""
  local usage=""
  local summary=""

  echo "| Command | Binary | Summary |"
  echo "| --- | --- | --- |"

  while IFS= read -r key; do
    [[ -n $key ]] || continue
    rows=""
    append_command_rows rows "$key" "${COMMAND_ROUTE[$key]}"
    while IFS=$'\t' read -r usage summary; do
      printf '| `%s` | `%s` | %s |\n' \
        "$(markdown_escape "$usage")" \
        "$(markdown_escape "${COMMAND_BINARY[$key]}")" \
        "$(markdown_escape "$summary")"
    done <<<"${rows%$'\n'}"
  done < <(sorted_keys "$include_all")
}

emit_command_record() {
  local key="$1"

  printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
    "${COMMAND_ROUTE[$key]}" \
    "${COMMAND_BINARY[$key]}" \
    "${COMMAND_GROUP[$key]}" \
    "${COMMAND_NAME[$key]}" \
    "${COMMAND_SUMMARY[$key]}" \
    "${COMMAND_REQUIRES_SUDO[$key]}" \
    "${COMMAND_HIDDEN[$key]}" \
    "${COMMAND_ARGS[$key]}" \
    "${COMMAND_EXAMPLES[$key]}" \
    "${COMMAND_ALIASES[$key]}" \
    "${COMMAND_FALLBACK_ROUTE[$key]}" \
    "${COMMAND_USAGE[$key]}"
}

emit_command_records() {
  local include_all="$1"
  local key=""

  while IFS= read -r key; do
    [[ -n $key ]] || continue
    emit_command_record "$key"
  done < <(sorted_keys "$include_all")
}

commands_json_filter() {
  cat <<'EOF'
[inputs | split("\t") | {
  route: .[0],
  binary: .[1],
  group: .[2],
  name: .[3],
  summary: .[4],
  requires_sudo: (.[5] == "true"),
  hidden: (.[6] == "true"),
  args: .[7],
  examples: (.[8] | split("|") | map(gsub("^ +| +$"; "")) | map(select(length > 0))),
  aliases: (.[9] | split("|") | map(gsub("^ +| +$"; "")) | map(select(length > 0))),
  filename_route: .[10],
  routes: ([.[0], .[10]] + (.[9] | split("|") | map(gsub("^ +| +$"; "")) | map(select(length > 0))) | unique)
}] | {ok: true, commands: .}
EOF
}

show_commands_json() {
  local include_all="$1"

  emit_command_records "$include_all" | jq -Rn "$(commands_json_filter)"
}

show_commands_check() {
  local failures=0
  local collision=""
  local key=""
  local error=""

  for collision in "${ROUTE_COLLISIONS[@]}"; do
    echo "Route collision: $collision" >&2
    failures=$((failures + 1))
  done

  for key in "${COMMAND_KEYS[@]}"; do
    if [[ ${COMMAND_HAS_SUMMARY[$key]} != "true" ]]; then
      echo "Missing metadata summary: ${COMMAND_BINARY[$key]}" >&2
      failures=$((failures + 1))
    fi

    if [[ -n ${COMMAND_METADATA_ERRORS[$key]} ]]; then
      while IFS= read -r error; do
        [[ -n $error ]] || continue
        echo "Invalid metadata in ${COMMAND_BINARY[$key]}: $error" >&2
        failures=$((failures + 1))
      done < <(pipe_values_as_lines "${COMMAND_METADATA_ERRORS[$key]}")
    fi

    if ! resolve_binary_path "${COMMAND_BINARY[$key]}"; then
      echo "Missing binary: ${COMMAND_BINARY[$key]}" >&2
      failures=$((failures + 1))
    fi
  done

  if (( failures > 0 )); then
    echo "Command metadata check failed ($failures issues)" >&2
    return 1
  fi

  echo "Command metadata check passed (${#COMMAND_KEYS[@]} commands)"
}

show_command_json() {
  emit_command_record "$1" | jq -Rn "$(commands_json_filter) | {ok: true, command: .commands[0]}"
}

parse_commands_args() {
  local include_all="false"
  local json="false"
  local markdown="false"
  local check="false"

  shift

  while (( $# > 0 )); do
    case "$1" in
    --all)
      include_all="true"
      ;;
    --json)
      json="true"
      ;;
    --markdown)
      markdown="true"
      ;;
    --check)
      check="true"
      ;;
    --help | -h)
      show_commands_help
      return 0
      ;;
    *)
      echo "Unknown option for omarchy commands: $1" >&2
      show_commands_help >&2
      return 2
      ;;
    esac
    shift
  done

  if [[ $check == "true" ]]; then
    OMARCHY_BIN_DIRS=("$OMARCHY_BIN_DIR")
  fi
  load_commands

  if [[ $check == "true" ]]; then
    show_commands_check
  elif [[ $json == "true" ]]; then
    show_commands_json "$include_all"
  elif [[ $markdown == "true" ]]; then
    show_commands_markdown "$include_all"
  else
    show_commands "$include_all"
  fi
}

group_exists() {
  local group="$1"
  local key=""

  for key in "${COMMAND_KEYS[@]}"; do
    if [[ ${COMMAND_GROUP[$key]} == "$group" && -n ${COMMAND_NAME[$key]} ]]; then
      return 0
    fi
  done

  return 1
}

show_group_help() {
  local group="$1"
  local include_all="${2:-false}"
  local key=""
  local rows=""
  local title="${GROUP_DESCRIPTIONS[$group]}"

  if [[ -n $title ]]; then
    echo "${group^} commands — $title:"
  else
    echo "${group^} commands:"
  fi

  while IFS= read -r key; do
    [[ -n $key ]] || continue
    append_command_rows rows "$key" "$(command_route_for_group "$key" "$group")"
  done < <(sorted_group_keys "$group" "$include_all")

  if [[ -n $rows ]]; then
    print_command_table "$rows"
  else
    echo "  No documented commands found. Try: omarchy commands --all"
  fi
}

show_prefix_help() {
  local prefix="$1"
  local prefix_with_space="$prefix "
  local key=""
  local rows=""

  while IFS= read -r key; do
    [[ -n $key ]] || continue
    if [[ ${COMMAND_USAGE[$key]} == "$prefix_with_space"* ]]; then
      append_command_rows rows "$key" "${COMMAND_ROUTE[$key]}"
    fi
  done < <(sorted_keys false)

  [[ -n $rows ]] || return 1

  echo "${prefix#omarchy } commands:"
  print_command_table "$rows"
}

show_related_commands() {
  local key="$1"
  local group="${COMMAND_GROUP[$key]}"
  local child_key=""
  local rows=""

  [[ -z ${COMMAND_NAME[$key]} ]] || return

  while IFS= read -r child_key; do
    [[ -n $child_key && $child_key != "$key" ]] || continue
    append_command_rows rows "$child_key" "$(command_route_for_group "$child_key" "$group")"
  done < <(sorted_group_keys "$group" false)

  if [[ -n $rows ]]; then
    echo ""
    echo "Related commands:"
    print_command_table "$rows"
  fi
}

show_command_help() {
  local key="$1"
  local aliases="${COMMAND_ALIASES[$key]}"
  local examples="${COMMAND_EXAMPLES[$key]}"
  local args="${COMMAND_ARGS[$key]}"
  local example=""
  local alias=""
  local rows=""

  echo "Usage:"
  if [[ -n ${COMMAND_SUBCOMMANDS[$key]} ]]; then
    append_command_rows rows "$key" "${COMMAND_ROUTE[$key]}"
    print_command_table "$rows"
  else
    echo "  ${COMMAND_USAGE[$key]}"
  fi
  echo ""
  echo "${COMMAND_SUMMARY[$key]}"

  if [[ -z ${COMMAND_SUBCOMMANDS[$key]} && -n $args ]]; then
    echo ""
    echo "Arguments:"
    echo "  $args"
  fi

  if [[ -n $examples ]]; then
    echo ""
    echo "Examples:"
    while IFS= read -r example; do
      printf '  %s\n' "$example"
    done < <(examples_as_lines "$examples")
  fi

  if [[ -n $aliases ]]; then
    echo ""
    echo "Aliases:"
    while IFS= read -r alias; do
      printf '  %s\n' "$alias"
    done < <(pipe_values_as_lines "$aliases")
  fi

  echo ""
  echo "Binary:"
  echo "  ${COMMAND_BINARY[$key]}"

  if [[ ${COMMAND_FALLBACK_ROUTE[$key]} != "${COMMAND_ROUTE[$key]}" ]]; then
    echo ""
    echo "Filename route:"
    echo "  ${COMMAND_FALLBACK_ROUTE[$key]}"
  fi

  show_related_commands "$key"
}

resolve_route() {
  local argc="$1"
  shift
  local args=("$@")
  local prefix_count=0
  local route=""
  local key=""

  for (( prefix_count = argc; prefix_count >= 1; prefix_count-- )); do
    route="omarchy $(join_words " " "${args[@]:0:prefix_count}")"
    key="${ROUTE_TO_KEY[$route]}"

    if [[ -n $key ]]; then
      RESOLVED_KEY="$key"
      RESOLVED_COUNT="$prefix_count"
      RESOLVED_ROUTE="$route"
      return 0
    fi
  done

  return 1
}

suggest_command() {
  local first="$1"
  local candidate=""

  for candidate in "${!ROUTE_TO_KEY[@]}"; do
    candidate="${candidate#omarchy }"
    if [[ $candidate == "$first"* ]]; then
      printf '%s' "${candidate%% *}"
      return 0
    fi
  done

  return 1
}

dispatch_fast_or_help() {
  local args=("$@")
  local remaining=()
  local key=""
  local binary_path=""

  if resolve_direct_route "$#" "${args[@]}"; then
    remaining=("${args[@]:DIRECT_RESOLVED_COUNT}")
    binary_path="$DIRECT_RESOLVED_PATH"

    if (( ${#remaining[@]} == 1 || ${#remaining[@]} == 2 )) && [[ ${remaining[0]} != -* ]] &&
      { (( ${#remaining[@]} == 1 )) || remaining_has_help_flag "${remaining[1]}"; } &&
      group_has_child_commands "${DIRECT_RESOLVED_BINARY#omarchy-}-${remaining[0]}"; then
      load_command_by_binary "$DIRECT_RESOLVED_BINARY"
      key="${BINARY_TO_KEY[$DIRECT_RESOLVED_BINARY]}"
      if [[ -n $key ]] && command_takes_only_flags "$key"; then
        load_commands
        show_prefix_help "$DIRECT_RESOLVED_ROUTE ${remaining[0]}" && return 0
      fi
    fi

    if remaining_has_help_flag "${remaining[@]}"; then
      if ! load_command_by_binary "$DIRECT_RESOLVED_BINARY"; then
        echo "Binary is missing or not executable: $DIRECT_RESOLVED_BINARY" >&2
        return 127
      fi

      if (( DIRECT_RESOLVED_COUNT == 1 )); then
        load_child_commands_by_binary "$DIRECT_RESOLVED_BINARY"
      fi

      key="${BINARY_TO_KEY[$DIRECT_RESOLVED_BINARY]}"
      if remaining_has_json_flag "${remaining[@]}"; then
        show_command_json "$key"
      else
        show_command_help "$key"
      fi
      return 0
    fi

    if (( ${#remaining[@]} == 0 )); then
      load_command_by_binary "$DIRECT_RESOLVED_BINARY"
      key="${BINARY_TO_KEY[$DIRECT_RESOLVED_BINARY]}"

      if [[ -n $key ]] && command_requires_args "$key"; then
        if (( DIRECT_RESOLVED_COUNT == 1 )) && group_has_child_commands "$1"; then
          load_group_commands "$1"
          show_group_help "$1"
          return 0
        else
          show_command_help "$key"
          return 1
        fi
      fi
    fi

    exec "$binary_path" "${remaining[@]}"
  fi

  if (( $# == 1 )) && group_has_binary_commands "$1"; then
    load_group_commands "$1"
    show_group_help "$1"
    return 0
  fi

  if (( $# >= 2 )) && [[ $2 == "--help" || $2 == "-h" ]] && group_has_binary_commands "$1"; then
    load_group_commands "$1"
    show_group_help "$1"
    return 0
  fi

  # Help lists related commands from the whole table, so only a route that runs
  # its command takes the candidates-only path.
  if ! remaining_has_help_flag "$@" && load_route_candidates "$1" && resolve_route "$#" "$@" &&
    ! { (( RESOLVED_COUNT == $# )) && command_requires_args "$RESOLVED_KEY"; }; then
    dispatch_or_help "$@"
    return
  fi

  reset_commands
  load_commands
  dispatch_or_help "$@"
}

dispatch_or_help() {
  local args=("$@")
  local remaining=()
  local key=""
  local binary_path=""
  local suggestion=""

  if resolve_route "$#" "${args[@]}"; then
    key="$RESOLVED_KEY"
    remaining=("${args[@]:RESOLVED_COUNT}")

    if remaining_has_help_flag "${remaining[@]}"; then
      if remaining_has_json_flag "${remaining[@]}"; then
        show_command_json "$key"
      else
        show_command_help "$key"
      fi
      return 0
    fi

    if ! resolve_binary_path "${COMMAND_BINARY[$key]}"; then
      echo "Binary is missing or not executable: ${COMMAND_BINARY[$key]}" >&2
      return 127
    fi
    binary_path="$RESOLVED_BINARY_PATH"

    if (( ${#remaining[@]} == 0 )) && command_requires_args "$key"; then
      if (( RESOLVED_COUNT == 1 )) && group_exists "$1"; then
        show_group_help "$1"
        return 0
      else
        show_command_help "$key"
        return 1
      fi
    fi

    exec "$binary_path" "${remaining[@]}"
  fi

  if (( $# == 1 )) && group_exists "$1"; then
    show_group_help "$1"
    return 0
  fi

  if (( $# >= 2 )) && [[ $2 == "--help" || $2 == "-h" ]] && group_exists "$1"; then
    show_group_help "$1"
    return 0
  fi

  if show_prefix_help "omarchy ${args[*]}"; then
    return 0
  fi

  echo "Unknown Armbian command: omarchy ${args[*]}" >&2
  suggestion=$(suggest_command "${args[0]}")
  if [[ -n $suggestion ]]; then
    echo "Did you mean: omarchy $suggestion ?" >&2
  fi
  echo "Run 'omarchy commands --all' to discover available commands." >&2
  return 127
}

main() {
  if (( $# == 0 )); then
    show_main_help
    return 0
  fi

  case "$1" in
  --help | -h)
    show_main_help
    ;;
  logout | reboot | shutdown)
    dispatch_fast_or_help system "$@"
    ;;
  commands)
    parse_commands_args "$@"
    ;;
  *)
    dispatch_fast_or_help "$@"
    ;;
  esac
}

main "$@"
