#!/usr/bin/env bash
# Android Release 打包脚本
#
# Usage:
#   bash scripts/build_android.sh apk               # APK（本地测试 / 内部分发）
#   bash scripts/build_android.sh aab               # AAB（Google Play 上架）
#   bash scripts/build_android.sh apk prod          # APK + prod 配置（CI 使用）
#   bash scripts/build_android.sh aab prod          # AAB + prod 配置（CI 使用）
#
# Via melos:
#   melos run build:android:apk
#   melos run build:android:aab
#
# 产物路径：
#   APK → apps/im_app/build/app/outputs/flutter-apk/app-release.apk
#   AAB → apps/im_app/build/app/outputs/bundle/release/app-release.aab
#   符号表 → apps/im_app/build/debug-info/android/（保留用于线上崩溃还原堆栈）

set -euo pipefail

FORMAT="${1:-apk}"
if [[ "$FORMAT" != "apk" && "$FORMAT" != "aab" ]]; then
  echo "Error: first argument must be 'apk' or 'aab'" >&2
  exit 1
fi

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/android"

# ── 可选：写入 prod 配置 ────────────────────────────────────────────────────
if [ "${2:-}" = "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

# ── 打包 ────────────────────────────────────────────────────────────────────
if [ "$FORMAT" = "aab" ]; then
  echo "==> Building Android release AAB (Google Play)..."
  cd "$APP_DIR"
  flutter build appbundle \
    --release \
    --no-pub \
    --dart-define-from-file=config/config.json \
    --split-debug-info="$DEBUG_INFO_DIR" \
    --obfuscate
  echo ""
  echo "✓ AAB: $APP_DIR/build/app/outputs/bundle/release/app-release.aab"
else
  echo "==> Building Android release APK..."
  cd "$APP_DIR"
  flutter build apk \
    --release \
    --no-pub \
    --dart-define-from-file=config/config.json \
    --split-debug-info="$DEBUG_INFO_DIR" \
    --obfuscate
  echo ""
  echo "✓ APK: $APP_DIR/build/app/outputs/flutter-apk/app-release.apk"
fi

echo "✓ 符号表: $DEBUG_INFO_DIR（请妥善保存，用于线上崩溃堆栈还原）"
