#!/bin/zsh
cd "$(dirname "$0")"
SERVER="${SCRIPT_WORKBENCH_SERVER:-https://script.hjmedia.online}"
CURRENT_VERSION="2026.06.14.8"

if command -v curl >/dev/null 2>&1 && command -v unzip >/dev/null 2>&1; then
  LATEST_VERSION=$(curl -fsSL "$SERVER/api/plugin-version" 2>/dev/null | sed -n 's/.*"version": *"\([^"]*\)".*/\1/p')
  if [[ -n "$LATEST_VERSION" && "$LATEST_VERSION" > "$CURRENT_VERSION" ]]; then
    echo "发现本地插件新版本：$LATEST_VERSION，正在自动更新..."
    TMP_DIR=$(mktemp -d)
    if curl -fL "$SERVER/downloads/script-workbench-local-plugin-mac.zip" -o "$TMP_DIR/plugin.zip" && unzip -q "$TMP_DIR/plugin.zip" -d "$TMP_DIR"; then
      cp -R "$TMP_DIR/ScriptWorkbenchLocalPlugin-Mac/." .
      chmod +x ./ScriptWorkbenchLocalPlugin-darwin-* ./start-mac.command 2>/dev/null
      echo "更新完成，正在启动新版插件。"
    else
      echo "自动更新失败，继续启动当前版本。"
    fi
    rm -rf "$TMP_DIR"
  fi
fi

if [[ "$(uname -m)" == "arm64" ]]; then
  ./ScriptWorkbenchLocalPlugin-darwin-arm64 8766
else
  ./ScriptWorkbenchLocalPlugin-darwin-amd64 8766
fi
