#!/usr/bin/env bash
# ------------------------------------------------------------------------------
# H5-in-App-Integration SDK · iOS 命令行构建入口
#
# 用法：
#   bash scripts/build-ios-swift.sh                  # = sdk：构建 TencentQianWebViewSDK framework
#   bash scripts/build-ios-swift.sh sdk              # 构建 TencentQianWebViewSDK framework (Release)
#   bash scripts/build-ios-swift.sh demo             # 构建 Demo app (Debug, Simulator)
#   bash scripts/build-ios-swift.sh all              # sdk + demo 全量 (Simulator)
#   bash scripts/build-ios-swift.sh device           # 构建 Demo app (Release, iOS Device, unsigned ipa)
#   bash scripts/build-ios-swift.sh xcframework      # 构建 TencentQianWebViewSDK.xcframework (device + simulator)
#   bash scripts/build-ios-swift.sh --help           # 查看本帮助
#
# 产物布局：
#   ios-swift/build/Build/Products/Release-iphoneos/TencentQianWebViewSDK.framework
#   ios-swift/build/Build/Products/Debug-iphonesimulator/Demo.app   (simulator)
#   ios-swift/build/Build/Products/Release-iphoneos/Demo.app          (device)
#   ios-swift/build/Demo.ipa                                        (device, unsigned)
#   ios-swift/build/TencentQianWebViewSDK.xcframework               (xcframework, device + simulator)
#
# 设计要点：
# - 使用 XcodeGen 生成 .xcodeproj（首次需要 brew install xcodegen）
# - 不需要真机签名（CODE_SIGNING_ALLOWED=NO）
# - 语言基线：Swift 5.9 / iOS 14.3+
# - xcframework 构建启用 BUILD_LIBRARY_FOR_DISTRIBUTION=YES 生成 swiftinterface，
#   模块名 TencentQianWebViewSDK ≠ enum 名 TencentQianWebView，无同名冲突。
# ------------------------------------------------------------------------------
set -euo pipefail

# ---- 路径与常量 --------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
IOS_DIR="${REPO_ROOT}/ios-swift"
BUILD_DIR="${IOS_DIR}/build"

# 从 CHANGELOG 读取版本号,构建时通过 xcodebuild MARKETING_VERSION=<ver> 注入 framework
# Info.plist 的 CFBundleShortVersionString,运行时由 SDK 读自身 Info.plist 获取。
SDK_VERSION="$("${SCRIPT_DIR}/extract-version.sh")"
echo "ℹ️  SDK 版本号（来自 CHANGELOG）：${SDK_VERSION}"

# ---- 提前处理 --help ---------------------------------------------------------
case "${1:-}" in
  -h|--help)
    sed -n '2,27p' "${BASH_SOURCE[0]}"
    exit 0
    ;;
esac

# ---- 工具链就绪检查 ----------------------------------------------------------
if ! command -v xcodebuild >/dev/null 2>&1; then
  echo "❌ 找不到 xcodebuild。请安装 Xcode Command Line Tools。" >&2
  exit 1
fi

if ! command -v xcodegen >/dev/null 2>&1; then
  echo "❌ 找不到 xcodegen。请执行：brew install xcodegen" >&2
  exit 1
fi

echo "ℹ️  iOS 项目目录：${IOS_DIR}"
echo "ℹ️  构建输出目录：${BUILD_DIR}"
echo ""

# ---- 生成 Xcode 项目 --------------------------------------------------------
echo "▶ 生成 Xcode 项目（xcodegen）..."
pushd "${IOS_DIR}" >/dev/null
xcodegen generate --quiet 2>/dev/null || xcodegen generate
popd >/dev/null

# ---- 构建函数 ----------------------------------------------------------------
build_sdk() {
  echo ""
  echo "▶ 构建 TencentQianWebViewSDK framework (Release) ..."
  xcodebuild build \
    -project "${IOS_DIR}/Demo.xcodeproj" \
    -scheme "TencentQianWebViewSDK" \
    -configuration Release \
    -derivedDataPath "${BUILD_DIR}" \
    MARKETING_VERSION="${SDK_VERSION}" \
    CODE_SIGNING_ALLOWED=NO \
    -quiet
  echo "✅ TencentQianWebViewSDK framework 构建完成"
}

build_demo() {
  echo ""
  echo "▶ 构建 Demo app (Debug, Simulator) ..."
  xcodebuild build \
    -project "${IOS_DIR}/Demo.xcodeproj" \
    -scheme "Demo" \
    -configuration Debug \
    -destination "generic/platform=iOS Simulator" \
    -derivedDataPath "${BUILD_DIR}" \
    MARKETING_VERSION="${SDK_VERSION}" \
    CODE_SIGNING_ALLOWED=NO \
    -quiet
  echo "✅ Demo app 构建完成"
}

# device：真机 arm64，Release（完整自包含二进制），unsigned，产出 .app 和 .ipa
#
# ⚠️ 关键：必须用 Release 而非 Debug！
#   Xcode 16+ 的 Debug 配置默认开启 ENABLE_DEBUG_DYLIB，会把 App 拆成:
#     Demo(空壳 launcher) + Demo.debug.dylib(真实代码) + __preview.dylib
#   这种包只能在 Xcode 调试器 attach 下运行, 独立安装到真机(如 WeTest 云测)
#   会因加载不到 debug dylib 而启动即崩溃, 导致自动化用例全部失败。
#   Release 配置产出单一自包含主二进制, 可独立运行。
build_demo_device() {
  echo ""
  echo "▶ 构建 Demo app (Release, iOS Device, unsigned) ..."
  xcodebuild build \
    -project "${IOS_DIR}/Demo.xcodeproj" \
    -scheme "Demo" \
    -configuration Release \
    -destination "generic/platform=iOS" \
    -derivedDataPath "${BUILD_DIR}" \
    MARKETING_VERSION="${SDK_VERSION}" \
    ENABLE_DEBUG_DYLIB=NO \
    CODE_SIGNING_ALLOWED=NO \
    CODE_SIGNING_REQUIRED=NO \
    CODE_SIGN_IDENTITY="" \
    CODE_SIGN_ENTITLEMENTS="" \
    -quiet

  local APP_PATH="${BUILD_DIR}/Build/Products/Release-iphoneos/Demo.app"
  if [[ ! -d "${APP_PATH}" ]]; then
    echo "❌ 找不到 Demo.app: ${APP_PATH}" >&2
    exit 1
  fi

  # 校验: 主二进制不应再依赖 .debug.dylib（否则真机独立运行会崩溃）
  if otool -L "${APP_PATH}/Demo" 2>/dev/null | grep -q "\.debug\.dylib"; then
    echo "❌ Demo 主二进制仍依赖 .debug.dylib, 这种包在真机独立运行会崩溃!" >&2
    echo "   请确认 ENABLE_DEBUG_DYLIB=NO 已生效。" >&2
    exit 1
  fi
  echo "✅ 校验通过: 主二进制为自包含结构, 无 .debug.dylib 依赖"

  local IPA_STAGE="${BUILD_DIR}/.ipa-stage"
  local IPA_OUT="${BUILD_DIR}/Demo.ipa"
  rm -rf "${IPA_STAGE}" "${IPA_OUT}"
  mkdir -p "${IPA_STAGE}/Payload"
  cp -R "${APP_PATH}" "${IPA_STAGE}/Payload/"
  ( cd "${IPA_STAGE}" && zip -qry "${IPA_OUT}" Payload )
  rm -rf "${IPA_STAGE}"

  echo "✅ Demo app (device) 构建完成：${IPA_OUT}"
  echo "ℹ️  IPA 为 unsigned, 上传 WeTest 时请确保勾选「开发者证书重签名」, 否则无法安装。"
}

# xcframework：分别构建 device + simulator 两个 Release framework slice，
# 再用 xcodebuild -create-xcframework 合成 .xcframework。
# 启用 BUILD_LIBRARY_FOR_DISTRIBUTION=YES 生成 swiftinterface，支持标准二进制分发。
# 解决 Apple Silicon Mac 上模拟器 arm64 与真机 arm64 冲突问题。
build_xcframework() {
  echo ""
  echo "▶ 构建 TencentQianWebViewSDK.xcframework (Release, device + simulator) ..."

  # ---- device slice (ios-arm64) ----
  echo "  ▷ 构建 device slice (ios-arm64) ..."
  xcodebuild build \
    -project "${IOS_DIR}/Demo.xcodeproj" \
    -scheme "TencentQianWebViewSDK" \
    -configuration Release \
    -destination "generic/platform=iOS" \
    -derivedDataPath "${BUILD_DIR}" \
    MARKETING_VERSION="${SDK_VERSION}" \
    CODE_SIGNING_ALLOWED=NO \
    BUILD_LIBRARY_FOR_DISTRIBUTION=YES \
    -quiet

  local DEVICE_FW="${BUILD_DIR}/Build/Products/Release-iphoneos/TencentQianWebViewSDK.framework"
  if [[ ! -d "${DEVICE_FW}" ]]; then
    echo "❌ 找不到 device framework: ${DEVICE_FW}" >&2
    exit 1
  fi

  # ---- simulator slice (ios-arm64_x86_64-simulator) ----
  echo "  ▷ 构建 simulator slice (ios-arm64_x86_64-simulator) ..."
  xcodebuild build \
    -project "${IOS_DIR}/Demo.xcodeproj" \
    -scheme "TencentQianWebViewSDK" \
    -configuration Release \
    -destination "generic/platform=iOS Simulator" \
    -derivedDataPath "${BUILD_DIR}" \
    MARKETING_VERSION="${SDK_VERSION}" \
    CODE_SIGNING_ALLOWED=NO \
    BUILD_LIBRARY_FOR_DISTRIBUTION=YES \
    -quiet

  local SIM_FW="${BUILD_DIR}/Build/Products/Release-iphonesimulator/TencentQianWebViewSDK.framework"
  if [[ ! -d "${SIM_FW}" ]]; then
    echo "❌ 找不到 simulator framework: ${SIM_FW}" >&2
    exit 1
  fi

  # ---- 合成 xcframework ----
  local XCFW_OUT="${BUILD_DIR}/TencentQianWebViewSDK.xcframework"
  rm -rf "${XCFW_OUT}"
  xcodebuild -create-xcframework \
    -framework "${DEVICE_FW}" \
    -framework "${SIM_FW}" \
    -output "${XCFW_OUT}"

  echo "✅ TencentQianWebViewSDK.xcframework 构建完成：${XCFW_OUT}"
  echo "   含 ios-arm64 (device) + ios-arm64_x86_64-simulator (simulator) 两个 slice"
}

# ---- 构建前清理上次产物（先清理再构建） --------------------------------------
echo "▶ 清理上次构建产物：${BUILD_DIR}"
rm -rf "${BUILD_DIR}"

# ---- 入口分发 ----------------------------------------------------------------
target="${1:-sdk}"
case "${target}" in
  sdk|"")
    build_sdk
    ;;
  demo)
    build_demo
    ;;
  device)
    build_demo_device
    ;;
  all)
    build_sdk
    build_demo
    ;;
  xcframework)
    build_xcframework
    ;;
  *)
    echo "❌ 未知参数：${target}" >&2
    echo "用法：bash scripts/build-ios-swift.sh [sdk|demo|device|all|xcframework]" >&2
    exit 1
    ;;
esac

echo ""
echo "🎉 iOS 构建完成！"
echo "   产物目录：${BUILD_DIR}/"
