#!/usr/bin/env bash
# macOS Release App 打包脚本
#
# Usage:
#   bash scripts/build_macos.sh                  # 使用默认 config（dev 配置）
#   bash scripts/build_macos.sh prod             # 写入 prod 配置后打包（CI 使用）
#
# Via melos:
#   melos run build:macos
#
# 产物路径：
#   .app → apps/im_app/build/macos/Build/Products/Release/im_app.app
#   符号表 → apps/im_app/build/debug-info/macos/

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(dirname "$SCRIPT_DIR")"
APP_DIR="$ROOT_DIR/apps/im_app"
CONFIG_FILE="$APP_DIR/config/config.json"
DEBUG_INFO_DIR="$APP_DIR/build/debug-info/macos"

# ── 可选：写入 prod 配置 ────────────────────────────────────────────────────
if [ "${1:-}" = "prod" ]; then
  echo "==> Writing prod config..."
  cat > "$CONFIG_FILE" <<EOF
{
  "IS_DEV": false,
  "API_BASE_URL": "${PROD_API_BASE_URL:?PROD_API_BASE_URL is not set}"
}
EOF
fi

# ── 打包 ────────────────────────────────────────────────────────────────────
echo "==> Building macOS release app..."
cd "$APP_DIR"

flutter build macos \
  --release \
  --no-pub \
  --dart-define-from-file=config/config.json \
  --split-debug-info="$DEBUG_INFO_DIR" \
  --obfuscate

echo ""
echo "✓ App: $APP_DIR/build/macos/Build/Products/Release/im_app.app"
echo "✓ 符号表: $DEBUG_INFO_DIR（请妥善保存，用于线上崩溃堆栈还原）"
