#!/usr/bin/env bash
# ------------------------------------------------------------------------------
# H5-in-App-Integration SDK · Android (Java) 命令行构建入口
#
# 用法：
#   bash scripts/build-android-java.sh              # = sdk：构建 webview-container AAR
#   bash scripts/build-android-java.sh sdk          # 构建 webview-container Release AAR
#   bash scripts/build-android-java.sh demo         # 构建 Demo APK (Debug)
#   bash scripts/build-android-java.sh all          # sdk + demo 全量
#   bash scripts/build-android-java.sh --help       # 查看本帮助
#
# 产物布局：
#   android-java/webview-container/build/outputs/aar/webview-container-release.aar
#   android-java/app/build/outputs/apk/debug/app-debug.apk
#
# 设计要点：
# - 使用 Gradle Wrapper（./gradlew），无需全局安装 Gradle
# - 双模块：:webview-container（SDK Library）/ :app（Demo Application）
# - 语言基线：Java 17 / Groovy DSL
# - 无 flavor 区分（单一产物）
# ------------------------------------------------------------------------------
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
ANDROID_DIR="${REPO_ROOT}/android-java"
GRADLEW="${ANDROID_DIR}/gradlew"

# 从 CHANGELOG 读取版本号
SDK_VERSION="$("${SCRIPT_DIR}/extract-version.sh")"
echo "ℹ️  SDK 版本号（来自 CHANGELOG）：${SDK_VERSION}"

case "${1:-}" in
  -h|--help)
    sed -n '2,22p' "${BASH_SOURCE[0]}"
    exit 0
    ;;
esac

if [[ ! -x "${GRADLEW}" ]]; then
  echo "❌ 找不到 gradlew：${GRADLEW}" >&2
  exit 1
fi

if [[ -z "${JAVA_HOME:-}" ]]; then
  if [[ -x "/usr/libexec/java_home" ]]; then
    export JAVA_HOME="$(/usr/libexec/java_home 2>/dev/null || true)"
  fi
fi

echo "ℹ️  Android Java 项目目录：${ANDROID_DIR}"

build_sdk() {
  echo "▶ 构建 webview-container Release AAR ..."
  "${GRADLEW}" -p "${ANDROID_DIR}" :webview-container:assembleRelease --no-daemon -PsdkVersion="${SDK_VERSION}"
}

build_demo() {
  echo "▶ 构建 Demo App Debug APK ..."
  "${GRADLEW}" -p "${ANDROID_DIR}" :app:assembleDebug --no-daemon -PsdkVersion="${SDK_VERSION}"
}

# ---- 构建前清理上次产物（先清理再构建） --------------------------------------
echo "▶ 清理上次构建产物：webview-container/build、app/build"
rm -rf "${ANDROID_DIR}/webview-container/build" "${ANDROID_DIR}/app/build"
echo ""

target="${1:-sdk}"
case "${target}" in
  sdk|"")   build_sdk ;;
  demo)     build_demo ;;
  all)      build_sdk; build_demo ;;
  *)        echo "❌ 未知参数：${target}"; exit 1 ;;
esac

echo ""
echo "🎉 Android Java 构建完成！"
echo "   SDK 产物目录：${ANDROID_DIR}/webview-container/build/outputs/aar/"
find "${ANDROID_DIR}/webview-container/build/outputs/aar/" -name "*.aar" -exec ls -lh {} \; 2>/dev/null || true
