#!/usr/bin/env bash
set -euo pipefail

ROOT="/Users/Shared/hermes-knowledge-engine"
SOURCE_DIR="$ROOT/deploy/launchd"
TARGET_DIR="$HOME/Library/LaunchAgents"
DOMAIN="gui/$(id -u)"
ACTION="${1:-status}"
shift || true

if [ "$#" -eq 0 ]; then
  SERVICES=(api worker)
else
  SERVICES=("$@")
fi

validate_service() {
  case "$1" in
    api|worker|watcher) ;;
    *) echo "Unknown service: $1" >&2; exit 2 ;;
  esac
}

label_for() {
  printf "com.neonlava.memory-cortex.%s" "$1"
}

plist_for() {
  printf "%s/%s.plist" "$TARGET_DIR" "$(label_for "$1")"
}

mkdir -p "$TARGET_DIR" "$ROOT/logs"

for service in "${SERVICES[@]}"; do
  validate_service "$service"
  label="$(label_for "$service")"
  plist="$(plist_for "$service")"

  case "$ACTION" in
    install)
      cp "$SOURCE_DIR/$label.plist" "$plist"
      launchctl bootout "$DOMAIN/$label" 2>/dev/null || true
      loaded=false
      for attempt in 1 2 3; do
        if launchctl bootstrap "$DOMAIN" "$plist"; then
          loaded=true
          break
        fi
        sleep "$attempt"
      done
      if [ "$loaded" != true ]; then
        echo "Failed to install $label" >&2
        exit 1
      fi
      echo "Installed $label"
      ;;
    uninstall)
      launchctl bootout "$DOMAIN/$label" 2>/dev/null || true
      rm -f "$plist"
      echo "Uninstalled $label"
      ;;
    restart)
      launchctl kickstart -k "$DOMAIN/$label"
      echo "Restarted $label"
      ;;
    status)
      if launchctl print "$DOMAIN/$label" >/dev/null 2>&1; then
        echo "$label: loaded"
      else
        echo "$label: not loaded"
      fi
      ;;
    *)
      echo "Usage: bin/cortex-services {install|uninstall|restart|status} [api|worker|watcher ...]" >&2
      exit 2
      ;;
  esac
done
