#!/bin/bash
# Sysadmin Agent — one-line installer for macOS (agent CLI + web UI).
#
#   curl -fsSL https://tea.ratsch.org/api/packages/hugh/generic/sysadmin-agent/0.4.0/install_macos.sh | bash
#
# Per-user install (no sudo, no root):
#   source + venv   ~/.local/share/sysadmin_agent
#   config          ~/.config/sysadmin_agent/env
#   binaries        ~/.local/bin/{sysagent,sysagent-webui}
#
# The web UI is installed with its dependencies by default and started with:
#   sysagent-webui run        # foreground
#   sysagent-webui install    # macOS LaunchAgent (auto-start at login)
#
# Options:
#   --local DIR     install from a local checkout instead of downloading the release
#   --version V     use a specific release version (default 0.4.0)
#   --dry-run       print every step, change nothing, skip the macOS check
set -euo pipefail

VERSION="${SYSAGENT_VERSION:-0.4.0}"
BASE_URL="https://tea.ratsch.org/api/packages/hugh/generic/sysadmin-agent/${VERSION}"
TAR="sysadmin-agent_${VERSION}_macos.tar.gz"
APP_ROOT="${SYSAGENT_HOME:-$HOME/.local/share/sysadmin_agent}"
CONFIG_DIR="$HOME/.config/sysadmin_agent"
ENV_FILE="$CONFIG_DIR/env"
BIN_DIR="$HOME/.local/bin"

DRY_RUN=0
LOCAL_DIR=""
for arg in "$@"; do
  case "$arg" in
    --dry-run) DRY_RUN=1 ;;
    --local=*) LOCAL_DIR="${arg#--local=}" ;;
    --version=*) VERSION="${arg#--version=}" ;;
    -h|--help) sed -n '2,22p' "$0"; exit 0 ;;
    *) echo "unknown argument: $arg (use --local=DIR, --version=V, --dry-run)" >&2; exit 2 ;;
  esac
done

say() { printf '\n=== %s ===\n' "$*"; }
run() {
  if [ "$DRY_RUN" = 1 ]; then printf '  [dry-run] %s\n' "$*"; else "$@"; fi
}

# ---------------------------------------------------------------- preflight
if [ "$DRY_RUN" = 0 ]; then
  if [ "$(uname -s)" != "Darwin" ]; then
    echo "ERROR: this is the macOS installer (host is $(uname -s)). On Linux use:" >&2
    echo "  curl -fsSL ${BASE_URL}/install.sh | bash" >&2
    exit 1
  fi
fi

say "Sysadmin Agent installer (macOS) — version ${VERSION}"

# Python 3.10+. Never guess the interpreter; refuse with a fix if absent.
PYBIN=""
for cand in python3.12 python3.11 python3.10 python3; do
  if command -v "$cand" >/dev/null 2>&1; then PYBIN="$(command -v "$cand")"; break; fi
done
if [ -z "$PYBIN" ]; then
  echo "ERROR: Python 3.10+ is required but not found." >&2
  echo "Install it with Homebrew first:  brew install python@3.12" >&2
  exit 1
fi
"$PYBIN" - <<'PY'
import sys
if sys.version_info < (3, 10):
    raise SystemExit(f"Python {sys.version.split()[0]} is too old; need >= 3.10")
print(f"  python: {sys.version.split()[0]} ({sys.executable})")
PY

# ---------------------------------------------------------------- fetch source
say "Source"
TMP_SRC=""
if [ -n "$LOCAL_DIR" ]; then
  [ -f "$LOCAL_DIR/webui/app.py" ] || { echo "ERROR: $LOCAL_DIR is not an agent checkout (no webui/app.py)" >&2; exit 1; }
  TMP_SRC="$LOCAL_DIR"
  echo "  installing from local checkout: $LOCAL_DIR"
else
  TMP_DL="$(mktemp -d)"
  trap 'rm -rf "$TMP_DL"' EXIT
  echo "  downloading ${TAR}..."
  run curl -fsSL -o "$TMP_DL/$TAR" "$BASE_URL/$TAR"
  mkdir -p "$TMP_DL/x"
  run tar xzf "$TMP_DL/$TAR" -C "$TMP_DL/x"
  TMP_SRC="$TMP_DL/x/sysadmin_agent"
fi

# ---------------------------------------------------------------- install source + venv
say "Install"
run mkdir -p "$APP_ROOT" "$CONFIG_DIR" "$BIN_DIR"
if command -v rsync >/dev/null 2>&1; then
  run rsync -a --exclude '.venv' --exclude '.env' "$TMP_SRC/" "$APP_ROOT/"
else
  run cp -R "$TMP_SRC/." "$APP_ROOT/"
fi

VENV="$APP_ROOT/.venv"
if [ ! -x "$VENV/bin/python" ]; then
  run "$PYBIN" -m venv "$VENV"
fi
run "$VENV/bin/python" -m pip install --upgrade pip
run "$VENV/bin/python" -m pip install -e "$APP_ROOT"
run "$VENV/bin/python" -m pip install -r "$APP_ROOT/requirements.txt"

# ---------------------------------------------------------------- config
say "Config"
if [ ! -f "$ENV_FILE" ]; then
  run cp "$APP_ROOT/.env.example" "$ENV_FILE"
  run chmod 600 "$ENV_FILE"
  echo "  created $ENV_FILE from example — set DEEPSEEK_API_KEY (or other provider)."
else
  echo "  $ENV_FILE already exists — left unchanged."
fi
# The web UI refuses to start without a token; generate one so it works out of the box.
if ! grep -qE '^[[:space:]]*SYSAGENT_WEB_TOKEN=.+' "$ENV_FILE" 2>/dev/null; then
  TOKEN="$(openssl rand -hex 24 2>/dev/null || "$PYBIN" -c 'import secrets;print(secrets.token_hex(24))')"
  if [ "$DRY_RUN" = 0 ]; then printf '\nSYSAGENT_WEB_TOKEN=%s\n' "$TOKEN" >>"$ENV_FILE"; fi
  echo "  generated SYSAGENT_WEB_TOKEN (${#TOKEN} chars)"
fi
run chmod 600 "$ENV_FILE"

# ---------------------------------------------------------------- PATH wrappers
say "Binaries"
# `sysagent` is pip's console script in the venv; symlink it. `sysagent-webui` is
# the shipped management script. Both land in ~/.local/bin (add it to PATH if needed).
run ln -sf "$VENV/bin/sysagent" "$BIN_DIR/sysagent"
run ln -sf "$APP_ROOT/bin/sysagent-webui" "$BIN_DIR/sysagent-webui"

# ---------------------------------------------------------------- done
say "Done"
cat <<EOF
  Sysadmin Agent ${VERSION} installed (per-user, no sudo).

  Next steps:
    1. Set your LLM key:  $ENV_FILE   (DEEPSEEK_API_KEY=…)
    2. Ensure $BIN_DIR is on your PATH:
         echo 'export PATH="\$HOME/.local/bin:\$PATH"' >> ~/.zshrc && source ~/.zshrc
    3. Try the CLI:       sysagent --dry-run "show disk usage"
    4. Start the web UI:
         sysagent-webui run            # foreground, http://0.0.0.0:8096
         sysagent-webui install        # LaunchAgent — auto-start at login
         sysagent-webui status         # check it
EOF
if ! case ":$PATH:" in *":$BIN_DIR:"*) true;; *) false;; esac; then
  echo ""
  echo "  NOTE: $BIN_DIR is not on your current PATH yet — run step 2, or use"
  echo "        $BIN_DIR/sysagent-webui run"
fi
