#!/usr/bin/env bash
# sysagent-webui — run and manage the Sysadmin Agent web UI.
#
# macOS-first (the Linux systemd unit `systemd/sysadmin-agent-webui.service` is the
# equivalent there); it also works from a Linux dev checkout. Installed to PATH by
# packaging/install_macos.sh. The web UI itself reads its config via the same dotenv
# discovery as the CLI (CWD .env, ~/.config/sysadmin_agent/env, /etc/sysadmin_agent/env),
# so this script never has to parse secrets — it just launches `python -m webui.app`.
#
#   sysagent-webui run          # foreground (default)
#   sysagent-webui install      # write + enable a macOS LaunchAgent (auto-start at login)
#   sysagent-webui uninstall    # remove the LaunchAgent
#   sysagent-webui start|stop|restart|status|logs
set -euo pipefail

# Resolve the real script path even through a symlink (macOS `readlink` has no `-f`).
_realpath() { python3 -c 'import os,sys;print(os.path.realpath(sys.argv[1]))' "$1" 2>/dev/null || printf '%s' "$1"; }

SCRIPT_REAL="$(_realpath "$0")"
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_REAL")" && pwd -P)"

# Locate the app tree (the directory that contains webui/app.py): SYSAGENT_HOME wins,
# else the checkout/install tree this script lives in (…/bin/.. or the repo root),
# else the default macOS install location.
APP_ROOT=""
for cand in "${SYSAGENT_HOME:-}" "$SCRIPT_DIR/.." "$SCRIPT_DIR" "$HOME/.local/share/sysadmin_agent"; do
  [ -n "$cand" ] || continue
  if [ -f "$cand/webui/app.py" ]; then APP_ROOT="$(cd "$cand" && pwd -P)"; break; fi
done
: "${APP_ROOT:?could not locate the agent app tree (webui/app.py); set SYSAGENT_HOME}"

PY="$APP_ROOT/.venv/bin/python"
[ -x "$PY" ] || PY="$(command -v python3 || true)"
: "${PY:?python3 not found — install Python 3.10+ (e.g. `brew install python`)}"

CONFIG_DIR="${SYSAGENT_CONFIG_DIR:-$HOME/.config/sysadmin_agent}"
ENV_FILE="$CONFIG_DIR/env"
LOG_DIR="$HOME/.local/share/sysadmin_agent/logs"
PLIST="$HOME/Library/LaunchAgents/com.sysadmin-agent.webui.plist"
LABEL="com.sysadmin-agent.webui"

# Warn (don't fail — the app's own check is authoritative) when the token is unset.
warn_config() {
  if [ -f "$ENV_FILE" ] && grep -qE '^[[:space:]]*SYSAGENT_WEB_TOKEN=.+' "$ENV_FILE"; then
    return 0
  fi
  echo "NOTE: SYSAGENT_WEB_TOKEN is not set in $ENV_FILE" >&2
  echo "      The web UI refuses to start without it. Add a token, e.g.:" >&2
  echo "        printf 'SYSAGENT_WEB_TOKEN=%s\n' \"\$(openssl rand -hex 24)\" >> \"$ENV_FILE\"" >&2
}

write_plist() {
  mkdir -p "$(dirname "$PLIST")" "$LOG_DIR"
  # plistlib does correct XML escaping for the (absolute) paths — no hand-rolled XML.
  PY="$PY" APP_ROOT="$APP_ROOT" PLIST="$PLIST" LABEL="$LABEL" LOG_DIR="$LOG_DIR" python3 - <<'PY'
import os, plistlib
pl = {
    "Label": os.environ["LABEL"],
    "ProgramArguments": [os.environ["PY"], "-m", "webui.app"],
    "WorkingDirectory": os.environ["APP_ROOT"],
    "RunAtLoad": True,
    "KeepAlive": True,
    "StandardOutPath": os.path.join(os.environ["LOG_DIR"], "webui.log"),
    "StandardErrorPath": os.path.join(os.environ["LOG_DIR"], "webui.err.log"),
}
with open(os.environ["PLIST"], "wb") as fh:
    plistlib.dump(pl, fh)
PY
  echo "wrote $PLIST"
}

is_macos() { [ "$(uname -s)" = "Darwin" ]; }

cmd="${1:-run}"
shift || true

case "$cmd" in
  run|"")
    warn_config
    cd "$APP_ROOT"
    echo "[sysagent-webui] app=$APP_ROOT python=$PY"
    exec "$PY" -m webui.app
    ;;
  install)
    is_macos || { echo "ERROR: launchctl is macOS-only; on Linux use the systemd unit instead." >&2; exit 1; }
    write_plist
    launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || true
    if launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/dev/null; then
      :
    else
      launchctl load "$PLIST"  # legacy fallback
    fi
    echo "installed LaunchAgent $LABEL (auto-starts at login)"
    echo "  status: sysagent-webui status"
    echo "  logs  : tail -f $LOG_DIR/webui.log"
    warn_config
    ;;
  uninstall)
    is_macos || { echo "ERROR: launchctl is macOS-only." >&2; exit 1; }
    launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
    rm -f "$PLIST"
    echo "removed $PLIST"
    ;;
  start)
    is_macos || { echo "ERROR: launchctl is macOS-only." >&2; exit 1; }
    [ -f "$PLIST" ] || write_plist
    launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/dev/null || launchctl load "$PLIST"
    echo "started $LABEL"
    ;;
  stop)
    is_macos || { echo "ERROR: launchctl is macOS-only." >&2; exit 1; }
    launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
    echo "stopped $LABEL"
    ;;
  restart)
    is_macos || { echo "ERROR: launchctl is macOS-only." >&2; exit 1; }
    launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || true
    launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/dev/null || launchctl load "$PLIST"
    echo "restarted $LABEL"
    ;;
  status)
    is_macos || { echo "ERROR: launchctl is macOS-only." >&2; exit 1; }
    launchctl print "gui/$(id -u)/$LABEL" 2>/dev/null || echo "$LABEL is not loaded (run: sysagent-webui install)"
    ;;
  logs)
    tail -n 100 -f "$LOG_DIR/webui.log" 2>/dev/null || echo "no log yet at $LOG_DIR/webui.log (run: sysagent-webui install)"
    ;;
  -h|--help|help)
    sed -n '2,12p' "$0"
    ;;
  *)
    echo "unknown command: $cmd" >&2
    sed -n '2,12p' "$0" >&2
    exit 2
    ;;
esac
