#!/usr/bin/env bash
# Input: Shell/SQL 运行环境、参数与运维约定
# Output: 可执行的本地/运维动作
# Pos: 主应用 / 静态交付层；资产子目录不要求 GEB 文件头 / install.sh

set -euo pipefail

ORIGIN="${STARVEIL_URL:-https://starveilai.com}"
ORIGIN="${ORIGIN%/}"
BIN_DIR="${STARVEIL_BIN_DIR:-$HOME/.local/bin}"
TARGET_BIN="$BIN_DIR/starveil"

echo "Installing StarVeil AI CLI & Agent Skills from ${ORIGIN}..."

if ! command -v node >/dev/null 2>&1; then
  echo "Error: Node.js 20+ is required to run the StarVeil CLI." >&2
  echo "Install Node.js from https://nodejs.org and re-run this script." >&2
  exit 1
fi

NODE_MAJOR="$(node -p "process.versions.node.split('.')[0]")"
if [ "${NODE_MAJOR:-0}" -lt 20 ]; then
  echo "Error: Node.js 20+ is required (found $(node -v))." >&2
  exit 1
fi

mkdir -p "$BIN_DIR"
TMP_FILE="$(mktemp)"
trap 'rm -f "$TMP_FILE"' EXIT

curl -fsSL "${ORIGIN}/downloads/starveil.mjs" -o "$TMP_FILE"
mv "$TMP_FILE" "$TARGET_BIN"
chmod 755 "$TARGET_BIN"

echo "Installed CLI -> ${TARGET_BIN}"

"$TARGET_BIN" install --target all >/dev/null 2>&1 || true
echo "Installed SKILL.md for Claude Code, Codex, Cursor & OpenClaw + native Antigravity plugin."

case ":${PATH}:" in
  *":${BIN_DIR}:"*) ;;
  *)
    echo ""
    echo "Add ${BIN_DIR} to your PATH to run 'starveil' from anywhere:"
    echo "  export PATH=\"${BIN_DIR}:\$PATH\""
    ;;
esac

echo ""
echo "Next steps:"
echo "  1. Antigravity: native plugin ready at ~/.gemini/config/plugins/starveil (auto-loaded on next turn)"
echo "  2. Claude Code (OAuth 2.1): claude mcp add --transport http starveil ${ORIGIN}/api/mcp"
echo "  3. Headless CLI / OpenClaw: create a sv_live_ key at ${ORIGIN}/app/agents, then run:"
echo "     ${TARGET_BIN} auth login --key sv_live_..."
echo "  4. Try it: ${TARGET_BIN} --help"
