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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
DIST_DIR="$ROOT_DIR/dist"
PKG_DIR="$DIST_DIR/mac-client-package"
APP_NAME="PinterestAIOperator"
APP_VERSION="$(node -e "console.log(require(process.argv[1]).version)" "$ROOT_DIR/package.json" 2>/dev/null || echo "0.0.0")"
APP_BUNDLE="$PKG_DIR/${APP_NAME}.app"
APP_RES="$APP_BUNDLE/Contents/Resources/app"
ZIP_PATH="$DIST_DIR/PinterestAIOperator-${APP_VERSION}-client-mac.zip"
LEGACY_ZIP_PATH="$DIST_DIR/PinterestAIOperator-client-mac.zip"

mkdir -p "$DIST_DIR"
rm -rf "$PKG_DIR" "$ZIP_PATH" "$LEGACY_ZIP_PATH"
mkdir -p "$APP_BUNDLE/Contents/MacOS" "$APP_RES"

cat > "$APP_BUNDLE/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleExecutable</key>
  <string>PinterestAIOperator</string>
  <key>CFBundleIdentifier</key>
  <string>com.pinterestauto.operator.client</string>
  <key>CFBundleName</key>
  <string>Pinterest AI Operator</string>
  <key>CFBundleDisplayName</key>
  <string>Pinterest AI Operator</string>
  <key>CFBundlePackageType</key>
  <string>APPL</string>
  <key>CFBundleShortVersionString</key>
  <string>${APP_VERSION}</string>
  <key>CFBundleVersion</key>
  <string>${APP_VERSION}</string>
</dict>
</plist>
PLIST

cat > "$APP_BUNDLE/Contents/MacOS/PinterestAIOperator" <<'LAUNCHER'
#!/bin/zsh
set -e

APP_DIR="$(cd "$(dirname "$0")/../Resources/app" && pwd)"
LOG_DIR="$HOME/Library/Logs/Pinterest AI Operator"
DATA_DIR="$HOME/Library/Application Support/Pinterest AI Operator"
mkdir -p "$LOG_DIR" "$DATA_DIR"

NODE_BIN="$(command -v node || true)"
if [ -z "$NODE_BIN" ]; then
  osascript -e 'display dialog "未找到 Node.js。请先安装 Node.js 20+，再重新打开 Pinterest AI Operator。" buttons {"OK"} default button "OK"'
  exit 1
fi

MAIN_PORT="${PINTEREST_AUTO_PORT:-3000}"
TRY_PORT="$MAIN_PORT"
while lsof -nP -iTCP:"$TRY_PORT" -sTCP:LISTEN >/dev/null 2>&1; do
  TRY_PORT=$((TRY_PORT + 1))
  if [ "$TRY_PORT" -gt $((MAIN_PORT + 20)) ]; then
    osascript -e 'display dialog "3000-3020 端口都被占用，请关闭旧的 Pinterest AI Operator 后重试。" buttons {"OK"} default button "OK"'
    exit 1
  fi
done
MAIN_PORT="$TRY_PORT"

cd "$APP_DIR"

if [ ! -f "$DATA_DIR/.env.local" ]; then
  cat > "$DATA_DIR/.env.local" <<EOF
PINTEREST_CLIENT_ID=
PINTEREST_CLIENT_SECRET=
PINTEREST_REDIRECT_URI=
PINTEREST_ACCESS_TOKEN=
OPENCLAW_SHARED_TOKEN=local-test-token
PINTEREST_AUTO_LICENSE_SERVER_URL=
PINTEREST_AUTO_REQUIRE_REMOTE_LICENSE=true
PINTEREST_AUTO_LICENSE_HEARTBEAT_TIMEOUT_MS=10000
PINTEREST_AUTO_UPDATE_MANIFEST_URL=
PINTEREST_AUTO_UPDATE_CHANNEL=stable
PINTEREST_AUTO_UPDATE_REQUIRE_SIGNATURE=true
PINTEREST_AUTO_UPDATE_PUBLIC_KEY_PATH=license-keys/update-public.pem
EOF
fi

if [ ! -f "$DATA_DIR/db.json" ]; then
  cp "packaging/default-db.json" "$DATA_DIR/db.json"
fi

set -a
. "$DATA_DIR/.env.local"
set +a

NEXT_DIST_DIR=.next \
PINTEREST_AUTO_DATA_DIR="$DATA_DIR" \
PORT="$MAIN_PORT" \
"$NODE_BIN" node_modules/next/dist/bin/next start > "$LOG_DIR/pinterest-auto.log" 2>&1 &
MAIN_PID=$!

sleep 3
open "http://127.0.0.1:${MAIN_PORT}"

osascript -e 'display dialog "Pinterest AI Operator 客户端已启动。\n\n主后台：http://127.0.0.1:'"$MAIN_PORT"'\n\n数据目录：'"$DATA_DIR"'\n\n远程授权请在商用授权区域填写 Web 云端授权地址和 License Key。" buttons {"OK"} default button "OK"'

wait "$MAIN_PID"
LAUNCHER

chmod +x "$APP_BUNDLE/Contents/MacOS/PinterestAIOperator"

rsync -a "$ROOT_DIR"/ "$APP_RES"/ \
  --exclude ".DS_Store" \
  --exclude ".env" \
  --exclude ".env.local" \
  --exclude ".next-dev/" \
  --exclude ".next-dev2/" \
  --exclude ".next-verify/" \
  --exclude ".next/cache/" \
  --exclude "data/db.json" \
  --exclude "license-keys/update-private.pem" \
  --exclude "/dist/" \
  --exclude "tsconfig.tsbuildinfo"

mkdir -p "$APP_RES/packaging"
node "$ROOT_DIR/scripts/write-default-db.mjs" "$APP_RES/packaging/default-db.json"

cat > "$APP_RES/README-MAC-CLIENT.txt" <<'README'
Pinterest AI Operator macOS 客户端

打开 PinterestAIOperator.app 后，应用会启动本机 Next 服务并打开浏览器。

注意：
- 需要本机已安装 Node.js 20+。
- 此客户端已启用云端远程授权；首次启动后填写 Web 云端授权服务器 URL 和 License Key。
- 商用动作会检查授权租约和每日额度。
- 远程更新会下载并校验更新包；替换应用由用户手动确认。
- 数据目录：~/Library/Application Support/Pinterest AI Operator
- 日志位置：~/Library/Logs/Pinterest AI Operator/pinterest-auto.log
README

(
  cd "$PKG_DIR"
  ditto -c -k --sequesterRsrc --keepParent "${APP_NAME}.app" "$ZIP_PATH"
)

cp "$ZIP_PATH" "$LEGACY_ZIP_PATH"
echo "$ZIP_PATH"
