#!/usr/bin/env bash
# ------------------------------------------------------------------------------
# H5-in-App-Integration SDK · iOS (Objective-C) 命令行构建入口
#
# 用法：
#   bash scripts/build-ios-objectivec.sh                  # = sdk：构建 TencentQianWebView framework
#   bash scripts/build-ios-objectivec.sh sdk              # 构建 TencentQianWebView framework (Release)
#   bash scripts/build-ios-objectivec.sh demo             # 构建 OC Demo app (Debug, Simulator)
#   bash scripts/build-ios-objectivec.sh demoswift        # 构建 DemoSwift app (Debug, Simulator, 纯 Swift 消费 OC SDK)
#   bash scripts/build-ios-objectivec.sh all              # sdk + OC Demo + DemoSwift 全量 (Simulator)
#   bash scripts/build-ios-objectivec.sh device           # 构建 OC Demo app (Release, iOS Device, unsigned ipa)
#   bash scripts/build-ios-objectivec.sh deviceswift      # 构建 DemoSwift app (Release, iOS Device, unsigned ipa)
#   bash scripts/build-ios-objectivec.sh xcframework      # 构建 TencentQianWebView.xcframework (device + simulator)
#   bash scripts/build-ios-objectivec.sh --help           # 查看本帮助
#
# 产物布局：
#   ios-objective-c/build/Build/Products/Release-iphoneos/TencentQianWebView.framework
#   ios-objective-c/build/Build/Products/Debug-iphonesimulator/Demo.app       (simulator, OC)
#   ios-objective-c/build/Build/Products/Debug-iphonesimulator/DemoSwift.app   (simulator, Swift)
#   ios-objective-c/build/Build/Products/Release-iphoneos/Demo.app             (device, OC)
#   ios-objective-c/build/Build/Products/Release-iphoneos/DemoSwift.app        (device, Swift)
#   ios-objective-c/build/Demo.ipa                                            (device, OC, unsigned)
#   ios-objective-c/build/DemoSwift.ipa                                       (device, Swift, unsigned)
#   ios-objective-c/build/TencentQianWebView.xcframework                      (xcframework, device + simulator)
#
# 设计要点：
# - 使用 XcodeGen 生成 .xcodeproj（首次需要 brew install xcodegen）
# - 工具链：Xcode 15+ / 纯 Objective-C / iOS 14.3+
# - 不需要真机签名（CODE_SIGNING_ALLOWED=NO）
# ------------------------------------------------------------------------------
set -euo pipefail

# ---- 路径与常量 --------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
IOS_DIR="${REPO_ROOT}/ios-objective-c"
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-OC 项目目录：${IOS_DIR}"
echo "ℹ️  构建输出目录：${BUILD_DIR}"
echo ""

# ---- 生成 Xcode 项目 --------------------------------------------------------
# 要求 xcodegen ≥ 2.45.0（projectFormat 选项）
XCODEGEN_MIN_REQUIRED="2.45.0"
XCODEGEN_VER="$(xcodegen --version 2>/dev/null | awk '{print $NF}')"
if [[ -z "${XCODEGEN_VER}" ]]; then
  echo "❌ 无法获取 xcodegen 版本，请确认安装：brew install xcodegen" >&2
  exit 1
fi
ver_lt() { [[ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | head -1)" == "$1" && "$1" != "$2" ]]; }
if ver_lt "${XCODEGEN_VER}" "${XCODEGEN_MIN_REQUIRED}"; then
  echo "❌ xcodegen ${XCODEGEN_VER} 过旧，要求 ≥ ${XCODEGEN_MIN_REQUIRED}。请：brew upgrade xcodegen" >&2
  exit 1
fi

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

# ---- 构建函数 ----------------------------------------------------------------
build_sdk() {
  echo ""
  echo "▶ 构建 TencentQianWebView framework (Release) ..."
  xcodebuild build \
    -project "${IOS_DIR}/Demo.xcodeproj" \
    -scheme "TencentQianWebView" \
    -configuration Release \
    -destination "generic/platform=iOS Simulator" \
    -derivedDataPath "${BUILD_DIR}" \
    MARKETING_VERSION="${SDK_VERSION}" \
    CODE_SIGNING_ALLOWED=NO \
    -quiet
  echo "✅ TencentQianWebView 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 构建完成"
}

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

# device：真机 arm64，Release（完整自包含二进制），unsigned，产出 .app 和 .ipa
#
# ⚠️ 关键：必须用 Release 而非 Debug！
#   Xcode 16+ 的 Debug 配置默认开启 ENABLE_DEBUG_DYLIB，会把 App 拆成
#   空壳 launcher + <App>.debug.dylib + __preview.dylib。这种包只能在 Xcode
#   调试器 attach 下运行, 独立安装到真机(如 WeTest 云测)会启动即崩溃,
#   导致自动化用例全部失败。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 时请确保勾选「开发者证书重签名」, 否则无法安装。"
}

# DemoSwift 真机构建：与 OC build_demo_device 同流程, 仅 scheme/产物名替换为 DemoSwift。
build_demo_swift_device() {
  echo ""
  echo "▶ 构建 DemoSwift app (Release, iOS Device, unsigned) ..."
  xcodebuild build \
    -project "${IOS_DIR}/Demo.xcodeproj" \
    -scheme "DemoSwift" \
    -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/DemoSwift.app"
  if [[ ! -d "${APP_PATH}" ]]; then
    echo "❌ 找不到 DemoSwift.app: ${APP_PATH}" >&2
    exit 1
  fi

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

  local IPA_STAGE="${BUILD_DIR}/.ipa-stage-swift"
  local IPA_OUT="${BUILD_DIR}/DemoSwift.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 "✅ DemoSwift app (device) 构建完成：${IPA_OUT}"
  echo "ℹ️  IPA 为 unsigned, 上传 WeTest 时请确保勾选「开发者证书重签名」, 否则无法安装。"
}

# xcframework：分别构建 device + simulator 两个 Release framework slice，
# 再用 xcodebuild -createXCFramework 合成 .xcframework。
# 解决 Apple Silicon Mac 上模拟器 arm64 与真机 arm64 冲突问题。
build_xcframework() {
  echo ""
  echo "▶ 构建 TencentQianWebView.xcframework (Release, device + simulator) ..."

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

  local DEVICE_FW="${BUILD_DIR}/Build/Products/Release-iphoneos/TencentQianWebView.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 "TencentQianWebView" \
    -configuration Release \
    -destination "generic/platform=iOS Simulator" \
    -derivedDataPath "${BUILD_DIR}" \
    MARKETING_VERSION="${SDK_VERSION}" \
    CODE_SIGNING_ALLOWED=NO \
    -quiet

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

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

  echo "✅ TencentQianWebView.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
    ;;
  demoswift)
    build_demo_swift
    ;;
  device)
    build_demo_device
    ;;
  deviceswift)
    build_demo_swift_device
    ;;
  all)
    build_sdk
    build_demo
    build_demo_swift
    ;;
  xcframework)
    build_xcframework
    ;;
  *)
    echo "❌ 未知参数：${target}" >&2
    echo "用法：bash scripts/build-ios-objectivec.sh [sdk|demo|demoswift|device|deviceswift|all|xcframework]" >&2
    exit 1
    ;;
esac

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