#!/bin/bash

# omarchy:summary=Shared helpers for editing ~/.config/omarchy/shell.json (source this, don't run it).
# omarchy:hidden=true

CONFIG_FILE="$HOME/.config/omarchy/shell.json"
DEFAULTS_FILE="$OMARCHY_PATH/config/omarchy/shell.json"

fail() {
  echo "${0##*/}: $*" >&2
  exit 1
}

refresh_shell_config() {
  if ! omarchy-shell shell reloadConfig >/dev/null 2>&1; then
    omarchy-shell -q shell rescanPlugins >/dev/null 2>&1 || true
  fi
}

source_file() {
  if [[ -s $CONFIG_FILE ]]; then
    printf '%s\n' "$CONFIG_FILE"
  else
    printf '%s\n' "$DEFAULTS_FILE"
  fi
}

# jq pipeline that normalizes shell.json into a well-shaped object with
# version=1, bar.layout.{left,center,right} arrays, and plugins array. Every
# mutation pipes through this so downstream jq can assume structure.
NORMALIZE='
  def object_or_empty: if type == "object" then . else {} end;
  def array_or_empty: if type == "array" then . else [] end;
  object_or_empty
  | .version = 1
  | .bar = (.bar | object_or_empty)
  | .bar.layout = (.bar.layout | object_or_empty)
  | .bar.layout.left = (.bar.layout.left | array_or_empty)
  | .bar.layout.center = (.bar.layout.center | array_or_empty)
  | .bar.layout.right = (.bar.layout.right | array_or_empty)
  | .plugins = (.plugins | array_or_empty)
'

# Apply a jq program to the source file and atomically write the result to the
# user config, then refresh the running shell. Extra args after the program are
# forwarded to jq (e.g. --arg/--argjson).
_SHELL_CONFIG_TMP=""
cleanup_shell_config_tmp() {
  if [[ -n $_SHELL_CONFIG_TMP ]]; then rm -f "$_SHELL_CONFIG_TMP"; fi
}
trap cleanup_shell_config_tmp EXIT

commit() {
  local program="$1"
  shift
  mkdir -p "$(dirname "$CONFIG_FILE")"
  _SHELL_CONFIG_TMP=$(mktemp)
  jq -S -e "$@" "$program" "$(source_file)" >"$_SHELL_CONFIG_TMP" || fail "could not update shell config"
  mv "$_SHELL_CONFIG_TMP" "$CONFIG_FILE"
  _SHELL_CONFIG_TMP=""
  refresh_shell_config
}
