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

# ==================================================================
# ★ CDN 配置 — 改这里 ★
# 脚本发布的 CDN 根路径（结尾无斜杠）
CDN_BASE="https://li-center.lixiang.com/livis-pc-kit/openclaw/mac-linux"
# ==================================================================

# ── 彩色日志 ──────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info()    { printf "${BLUE}[setup]${NC} %s\n" "$*"; }
log_success() { printf "${GREEN}[setup]${NC} %s\n" "$*"; }
log_warn()    { printf "${YELLOW}[setup] WARN:${NC} %s\n" "$*" >&2; }
log_error()   { printf "${RED}[setup] ERROR:${NC} %s\n" "$*" >&2; }

# ── 辅助函数 ──────────────────────────────────────────────────────
usage() {
  cat <<'USAGE'
Usage:
  ./setup.sh --openclaw [install|uninstall|update] [--version <ver>]

Architecture:
  --openclaw    Use OpenClaw plugin architecture

Operations:
  install       Install plugin and skills (default)
  uninstall     Uninstall plugin and skills
  update        Update plugin and skills (uninstall + install)

Options:
  --version <ver>   Pin to a specific release (e.g. v1.1.50). Default: latest
  -h, --help        Show this help message

Examples:
  ./setup.sh --openclaw
  ./setup.sh --openclaw install
  ./setup.sh --openclaw update
  ./setup.sh --openclaw uninstall
  ./setup.sh --openclaw install --version v1.1.50
USAGE
}

need_value() {
  local opt="$1"
  local val="${2:-}"
  if [ -z "$val" ]; then
    log_error "missing value for $opt"
    exit 1
  fi
}

need_next_arg() {
  local opt="$1"
  local argc="$2"
  if [ "$argc" -lt 2 ]; then
    log_error "missing value for $opt"
    exit 1
  fi
}

# ── 参数解析 ──────────────────────────────────────────────────────
ARCH=""
OP="install"
VERSION="latest"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --openclaw)
      ARCH="openclaw"
      ;;
    install|uninstall|update)
      OP="$1"
      ;;
    --version)
      need_next_arg "--version" $#
      VERSION="$2"
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      log_error "unknown option: $1"
      usage
      exit 1
      ;;
  esac
  shift
done

if [ -z "$ARCH" ]; then
  log_error "architecture is required (--openclaw)"
  usage
  exit 1
fi

# ── 动态构建 CDN URL（根据版本参数）────────────────────────────────
if [ "$VERSION" = "latest" ]; then
  INSTALL_PLUGIN_CDN_URL="${CDN_BASE}/latest/install-plugin.sh"
  INSTALL_SKILLS_CDN_URL="${CDN_BASE}/latest/install-skills.sh"
else
  INSTALL_PLUGIN_CDN_URL="${CDN_BASE}/versions/${VERSION}/install-plugin.sh"
  INSTALL_SKILLS_CDN_URL="${CDN_BASE}/versions/${VERSION}/install-skills.sh"
fi

# ── 主流程 ────────────────────────────────────────────────────────
log_info "architecture: $ARCH  operation: $OP  version: $VERSION"

# 串行执行：先装插件，再装 skills
log_info "==> running plugin installer..."
bash <(curl -fsSL "$INSTALL_PLUGIN_CDN_URL") "$ARCH" "$OP"

log_info "==> running skills installer..."
bash <(curl -fsSL "$INSTALL_SKILLS_CDN_URL") "$ARCH" "$OP"

log_success "$ARCH $OP completed successfully"

# ── 安装后：提示用户在手机 APP 绑定 Agent ID ─────────────────
if [[ "$OP" == "install" || "$OP" == "update" ]]; then
  OPENCLAW_DIR="${OPENCLAW_DIR:-$HOME/.openclaw}"
  AGENT_ID_FILE="$OPENCLAW_DIR/livis-agent.id"
  # 等待 gateway 启动并写入 livis-agent.id（最多 30 秒）
  log_info "waiting for agent ID..."
  for i in $(seq 1 30); do
    if [ -f "$AGENT_ID_FILE" ] && [ -s "$AGENT_ID_FILE" ]; then
      break
    fi
    sleep 1
  done
  if [ -f "$AGENT_ID_FILE" ] && [ -f "$OPENCLAW_DIR/livis-pc-kit-tokens.json" ]; then
    AGENT_ID="$(cat "$AGENT_ID_FILE" | tr -d '[:space:]')"
    if [ -n "$AGENT_ID" ]; then
      printf "\n"
      printf "${GREEN}========================================${NC}\n"
      printf "${GREEN}  Agent ID: ${YELLOW}%s${NC}\n" "$AGENT_ID"
      printf "${GREEN}========================================${NC}\n"
      printf "${BLUE}[setup]${NC} Open the mobile APP and enter the Agent ID above on the device binding page to complete binding. You can skip this if already bound.\n"
      printf "\n"
    fi
  fi
fi

