#!/usr/bin/env bash
# ------------------------------------------------------------------------------
# H5-in-App-Integration SDK · iOS SPM + xcframework 集成验证脚本
#
# 用途：
#   自动验证 iOS SDK 的两种集成方式：
#   - SPM Add Local：Swift 版 + OC 版均通过 Add Local 引入并编译（device + simulator）
#   - xcframework：Swift 版 + OC 版的 .xcframework 均可拖入空白工程并编译
#     （device + simulator，Apple Silicon 无冲突）
#
# 用法：
#   bash scripts/verify-ios-integration.sh              # = all：全量验证
#   bash scripts/verify-ios-integration.sh spm           # 仅验证 SPM Add Local
#   bash scripts/verify-ios-integration.sh xcframework   # 仅验证 xcframework 集成
#   bash scripts/verify-ios-integration.sh all           # 全量验证
#   bash scripts/verify-ios-integration.sh --help        # 查看本帮助
#
# 验证矩阵：
#   ┌──────────┬──────────────┬────────────────────────────────────────────┬────────────┐
#   │ 集成方式 │ SDK 版本      │ 消费方式                                     │ 架构       │
#   ├──────────┼──────────────┼────────────────────────────────────────────┼────────────┤
#   │ SPM      │ Swift 版     │ Swift app: import TencentQianWebViewSDK    │ sim + dev │
#   │ SPM      │ OC 版        │ Swift app: import TencentQianWebView       │ sim + dev │
#   │ SPM      │ OC 版        │ OC app: @import TencentQianWebView         │ sim + dev │
#   │ xcframework │ Swift 版  │ Swift app: import TencentQianWebViewSDK    │ sim + dev │
#   │ xcframework │ OC 版     │ Swift app: import TencentQianWebView       │ sim + dev │
#   │ xcframework │ OC 版     │ OC app: #import <TencentQianWebView/...>   │ sim + dev │
#   └──────────┴──────────────┴────────────────────────────────────────────┴────────────┘
#
# 原理：
#   在临时目录创建最小化空白 Xcode 工程（xcodegen 生成），添加 SPM 本地包或
#   xcframework 依赖，然后用 xcodebuild 分别构建 simulator + device slice。
#   全程 CODE_SIGNING_ALLOWED=NO，无需开发者证书。
#
# 依赖：
#   - Xcode 15+ (xcodebuild)
#   - xcodegen ≥ 2.45.0 (brew install xcodegen)
# ------------------------------------------------------------------------------
set -euo pipefail

# ---- 路径与常量 --------------------------------------------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
IOS_SWIFT_DIR="${REPO_ROOT}/ios-swift"
IOS_OC_DIR="${REPO_ROOT}/ios-objective-c"
TMP_BASE="$(mktemp -d -t ios-verify-XXXXXX)"
PASS_COUNT=0
FAIL_COUNT=0
TOTAL_COUNT=0

trap 'rm -rf "${TMP_BASE}"' EXIT

# ---- 颜色输出 ----------------------------------------------------------------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

print_pass() { echo -e "  ${GREEN}✅ PASS${NC} $1"; PASS_COUNT=$((PASS_COUNT + 1)); }
print_fail() { echo -e "  ${RED}❌ FAIL${NC} $1"; FAIL_COUNT=$((FAIL_COUNT + 1)); }
print_info() { echo -e "  ${CYAN}ℹ️${NC}  $1"; }
print_step() { echo -e "\n${BOLD}${YELLOW}▶ $1${NC}"; }

# ---- 工具链检查 --------------------------------------------------------------
check_tools() {
  echo "▶ 工具链检查"
  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
  XCODEGEN_VER="$(xcodegen --version 2>/dev/null | awk '{print $NF}')"
  ver_lt() { [[ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | head -1)" == "$1" && "$1" != "$2" ]]; }
  if ver_lt "${XCODEGEN_VER}" "2.45.0"; then
    echo "❌ xcodegen ${XCODEGEN_VER} 过旧，要求 ≥ 2.45.0。请：brew upgrade xcodegen" >&2
    exit 1
  fi
  echo "✅ xcodebuild + xcodegen ${XCODEGEN_VER} 就绪"
  echo "ℹ️  临时目录：${TMP_BASE}"
}

# ---- 构建函数 ----------------------------------------------------------------

# 构建 simulator + device 两个 slice
# 参数：$1=项目目录 $2=scheme名 $3=derivedDataPath
build_both() {
  local proj_dir="$1"
  local scheme="$2"
  local dd_path="$3"
  local sim_ok="false"
  local dev_ok="false"

  # ---- 先解析 SPM 包依赖 ----
  print_info "解析 SPM 包依赖 ..."
  xcodebuild \
    -project "${proj_dir}/Verify.xcodeproj" \
    -scheme "${scheme}" \
    -resolvePackageDependencies \
    -derivedDataPath "${dd_path}" 2>&1 | tail -3 || true

  # ---- Simulator ----
  TOTAL_COUNT=$((TOTAL_COUNT + 1))
  print_info "构建 Simulator (arm64_x86_64-simulator) ..."
  if xcodebuild build \
    -project "${proj_dir}/Verify.xcodeproj" \
    -scheme "${scheme}" \
    -configuration Release \
    -destination "generic/platform=iOS Simulator" \
    -derivedDataPath "${dd_path}" \
    CODE_SIGNING_ALLOWED=NO \
    -quiet 2>&1 | tail -5; then
    print_pass "Simulator 构建"
    sim_ok="true"
  else
    print_fail "Simulator 构建"
  fi

  # ---- Device ----
  TOTAL_COUNT=$((TOTAL_COUNT + 1))
  print_info "构建 Device (arm64) ..."
  if xcodebuild build \
    -project "${proj_dir}/Verify.xcodeproj" \
    -scheme "${scheme}" \
    -configuration Release \
    -destination "generic/platform=iOS" \
    -derivedDataPath "${dd_path}" \
    CODE_SIGNING_ALLOWED=NO \
    CODE_SIGNING_REQUIRED=NO \
    CODE_SIGN_IDENTITY="" \
    -quiet 2>&1 | tail -5; then
    print_pass "Device 构建"
    dev_ok="true"
  else
    print_fail "Device 构建"
  fi

  # Apple Silicon arm64 冲突专项检查（仅 simulator slice）
  if [[ "${sim_ok}" == "true" ]]; then
    TOTAL_COUNT=$((TOTAL_COUNT + 1))
    local sim_app="${dd_path}/Build/Products/Release-iphonesimulator/VerifyApp.app"
    if [[ -d "${sim_app}" ]]; then
      local sim_binary="${sim_app}/VerifyApp"
      if [[ -f "${sim_binary}" ]]; then
        local archs
        archs="$(lipo -archs "${sim_binary}" 2>/dev/null || echo "unknown")"
        if echo "${archs}" | grep -q "arm64"; then
          print_pass "Apple Silicon arm64 simulator slice 无冲突 (archs: ${archs})"
        else
          print_pass "Simulator binary archs: ${archs}"
        fi
      else
        print_pass "Simulator app 产物存在"
      fi
    else
      # 可能在别的路径
      print_pass "Simulator 构建成功（arm64 冲突检查跳过：未定位 app 产物）"
    fi
  fi
}

# ==============================================================================
# SPM Add Local 验证
# ==============================================================================

verify_spm_swift() {
  print_step "SPM Add Local · Swift 版 → Swift 消费者"

  local work_dir="${TMP_BASE}/spm-swift"
  mkdir -p "${work_dir}/src"

  # ---- 最小化 Swift app 源码 ----
  cat > "${work_dir}/src/VerifyApp.swift" << 'SWIFT_EOF'
import UIKit
import TencentQianWebViewSDK

@main
final class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        let label = UILabel()
        label.text = "SDK Version: \(TencentQianWebView.sdkVersion)"
        label.textAlignment = .center
        let vc = UIViewController()
        vc.view.backgroundColor = .white
        vc.view.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor)
        ])
        window?.rootViewController = vc
        window?.makeKeyAndVisible()
        return true
    }
}
SWIFT_EOF

  # ---- xcodegen project.yml ----
  cat > "${work_dir}/project.yml" << YAML_EOF
name: Verify
options:
  bundleIdPrefix: com.verify.spm.swift
  deploymentTarget:
    iOS: "11.0"
  createIntermediateGroups: true
  projectFormat: xcode15_0
packages:
  TencentQianWebViewSDK:
    path: ${IOS_SWIFT_DIR}
targets:
  VerifyApp:
    type: application
    platform: iOS
    sources:
      - path: src
    dependencies:
      - package: TencentQianWebViewSDK
    settings:
      base:
        # Xcode 26 SPM 构建 Swift swiftmodule 时会将 .iOS(.v11) clamp 到
        # Xcode 最低支持版本(12.0)，consumer 部署目标必须 ≥ 12.0 才能 import。
        # SDK 自身 Package.swift 仍声明 .iOS(.v11)（仅 warning）。
        IPHONEOS_DEPLOYMENT_TARGET: "12.0"
        PRODUCT_BUNDLE_IDENTIFIER: com.verify.spm.swift.app
        GENERATE_INFOPLIST_FILE: "YES"
        SWIFT_VERSION: "5.9"
        TARGETED_DEVICE_FAMILY: "1,2"
        CODE_SIGNING_ALLOWED: "NO"
schemes:
  VerifyApp:
    build:
      targets:
        VerifyApp: all
YAML_EOF

  print_info "生成 Xcode 工程 (xcodegen) ..."
  (cd "${work_dir}" && xcodegen generate --quiet 2>/dev/null) || (cd "${work_dir}" && xcodegen generate)

  build_both "${work_dir}" "VerifyApp" "${work_dir}/build"
}

verify_spm_oc_swift_consumer() {
  print_step "SPM Add Local · OC 版 → Swift 消费者"

  local work_dir="${TMP_BASE}/spm-oc-swift"
  mkdir -p "${work_dir}/src"

  cat > "${work_dir}/src/VerifyApp.swift" << 'SWIFT_EOF'
import UIKit
import TencentQianWebView

@main
final class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        let label = UILabel()
        label.text = "OC SDK via SPM, Swift consumer"
        label.textAlignment = .center
        let vc = UIViewController()
        vc.view.backgroundColor = .white
        vc.view.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor)
        ])
        window?.rootViewController = vc
        window?.makeKeyAndVisible()
        return true
    }
}
SWIFT_EOF

  cat > "${work_dir}/project.yml" << YAML_EOF
name: Verify
options:
  bundleIdPrefix: com.verify.spm.oc.swift
  deploymentTarget:
    iOS: "11.0"
  createIntermediateGroups: true
  projectFormat: xcode15_0
packages:
  TencentQianWebView:
    path: ${IOS_OC_DIR}
targets:
  VerifyApp:
    type: application
    platform: iOS
    sources:
      - path: src
    dependencies:
      - package: TencentQianWebView
    settings:
      base:
        PRODUCT_BUNDLE_IDENTIFIER: com.verify.spm.oc.swift.app
        GENERATE_INFOPLIST_FILE: "YES"
        SWIFT_VERSION: "5.9"
        TARGETED_DEVICE_FAMILY: "1,2"
        CODE_SIGNING_ALLOWED: "NO"
schemes:
  VerifyApp:
    build:
      targets:
        VerifyApp: all
YAML_EOF

  print_info "生成 Xcode 工程 (xcodegen) ..."
  (cd "${work_dir}" && xcodegen generate --quiet 2>/dev/null) || (cd "${work_dir}" && xcodegen generate)

  build_both "${work_dir}" "VerifyApp" "${work_dir}/build"
}

verify_spm_oc_oc_consumer() {
  print_step "SPM Add Local · OC 版 → OC 消费者"

  local work_dir="${TMP_BASE}/spm-oc-oc"
  mkdir -p "${work_dir}/src"

  cat > "${work_dir}/src/main.m" << 'OBJC_EOF'
#import <UIKit/UIKit.h>
@import TencentQianWebView;

@interface VerifyAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

@implementation VerifyAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [[UIViewController alloc] init];
    [self.window makeKeyAndVisible];
    return YES;
}
@end

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, @"VerifyAppDelegate");
    }
}
OBJC_EOF

  cat > "${work_dir}/project.yml" << YAML_EOF
name: Verify
options:
  bundleIdPrefix: com.verify.spm.oc.oc
  deploymentTarget:
    iOS: "11.0"
  createIntermediateGroups: true
  projectFormat: xcode15_0
packages:
  TencentQianWebView:
    path: ${IOS_OC_DIR}
targets:
  VerifyApp:
    type: application
    platform: iOS
    sources:
      - path: src
    dependencies:
      - package: TencentQianWebView
    settings:
      base:
        PRODUCT_BUNDLE_IDENTIFIER: com.verify.spm.oc.oc.app
        GENERATE_INFOPLIST_FILE: "YES"
        CLANG_ENABLE_MODULES: "YES"
        CLANG_ENABLE_OBJC_ARC: "YES"
        TARGETED_DEVICE_FAMILY: "1,2"
        CODE_SIGNING_ALLOWED: "NO"
schemes:
  VerifyApp:
    build:
      targets:
        VerifyApp: all
YAML_EOF

  print_info "生成 Xcode 工程 (xcodegen) ..."
  (cd "${work_dir}" && xcodegen generate --quiet 2>/dev/null) || (cd "${work_dir}" && xcodegen generate)

  build_both "${work_dir}" "VerifyApp" "${work_dir}/build"
}

# ==============================================================================
# xcframework 集成验证
# ==============================================================================

verify_xcframework_swift() {
  print_step "xcframework · Swift 版 → Swift 消费者"

  local xcframework="${IOS_SWIFT_DIR}/build/TencentQianWebViewSDK.xcframework"
  if [[ ! -d "${xcframework}" ]]; then
    echo -e "  ${YELLOW}⚠️  Swift xcframework 不存在，先构建...${NC}"
    bash "${SCRIPT_DIR}/build-ios-swift.sh" xcframework
  fi
  if [[ ! -d "${xcframework}" ]]; then
    print_fail "Swift xcframework 构建失败，跳过"
    TOTAL_COUNT=$((TOTAL_COUNT + 3))
    FAIL_COUNT=$((FAIL_COUNT + 3))
    return
  fi

  # 验证 slice 完整性
  TOTAL_COUNT=$((TOTAL_COUNT + 1))
  local slices
  slices="$(ls "${xcframework}" | grep -E '^ios-' || true)"
  if echo "${slices}" | grep -q "ios-arm64" && echo "${slices}" | grep -q "simulator"; then
    print_pass "xcframework slice 完整: $(echo "${slices}" | tr '\n' ' ')"
  else
    print_fail "xcframework slice 缺失: ${slices}"
  fi

  local work_dir="${TMP_BASE}/xcfw-swift"
  mkdir -p "${work_dir}/src"

  cat > "${work_dir}/src/VerifyApp.swift" << 'SWIFT_EOF'
import UIKit
import TencentQianWebViewSDK

@main
final class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        let label = UILabel()
        label.text = "SDK Version: \(TencentQianWebView.sdkVersion)"
        label.textAlignment = .center
        let vc = UIViewController()
        vc.view.backgroundColor = .white
        vc.view.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor)
        ])
        window?.rootViewController = vc
        window?.makeKeyAndVisible()
        return true
    }
}
SWIFT_EOF

  cat > "${work_dir}/project.yml" << YAML_EOF
name: Verify
options:
  bundleIdPrefix: com.verify.xcfw.swift
  deploymentTarget:
    iOS: "11.0"
  createIntermediateGroups: true
  projectFormat: xcode15_0
targets:
  VerifyApp:
    type: application
    platform: iOS
    sources:
      - path: src
    dependencies:
      - framework: ${xcframework}
        embed: true
    settings:
      base:
        PRODUCT_BUNDLE_IDENTIFIER: com.verify.xcfw.swift.app
        GENERATE_INFOPLIST_FILE: "YES"
        SWIFT_VERSION: "5.9"
        TARGETED_DEVICE_FAMILY: "1,2"
        CODE_SIGNING_ALLOWED: "NO"
schemes:
  VerifyApp:
    build:
      targets:
        VerifyApp: all
YAML_EOF

  print_info "生成 Xcode 工程 (xcodegen) ..."
  (cd "${work_dir}" && xcodegen generate --quiet 2>/dev/null) || (cd "${work_dir}" && xcodegen generate)

  build_both "${work_dir}" "VerifyApp" "${work_dir}/build"
}

verify_xcframework_oc_swift_consumer() {
  print_step "xcframework · OC 版 → Swift 消费者"

  local xcframework="${IOS_OC_DIR}/build/TencentQianWebView.xcframework"
  if [[ ! -d "${xcframework}" ]]; then
    echo -e "  ${YELLOW}⚠️  OC xcframework 不存在，先构建...${NC}"
    bash "${SCRIPT_DIR}/build-ios-objectivec.sh" xcframework
  fi
  if [[ ! -d "${xcframework}" ]]; then
    print_fail "OC xcframework 构建失败，跳过"
    TOTAL_COUNT=$((TOTAL_COUNT + 3))
    FAIL_COUNT=$((FAIL_COUNT + 3))
    return
  fi

  TOTAL_COUNT=$((TOTAL_COUNT + 1))
  local slices
  slices="$(ls "${xcframework}" | grep -E '^ios-' || true)"
  if echo "${slices}" | grep -q "ios-arm64" && echo "${slices}" | grep -q "simulator"; then
    print_pass "xcframework slice 完整: $(echo "${slices}" | tr '\n' ' ')"
  else
    print_fail "xcframework slice 缺失: ${slices}"
  fi

  local work_dir="${TMP_BASE}/xcfw-oc-swift"
  mkdir -p "${work_dir}/src"

  cat > "${work_dir}/src/VerifyApp.swift" << 'SWIFT_EOF'
import UIKit
import TencentQianWebView

@main
final class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        let label = UILabel()
        label.text = "OC xcframework, Swift consumer"
        label.textAlignment = .center
        let vc = UIViewController()
        vc.view.backgroundColor = .white
        vc.view.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor)
        ])
        window?.rootViewController = vc
        window?.makeKeyAndVisible()
        return true
    }
}
SWIFT_EOF

  cat > "${work_dir}/project.yml" << YAML_EOF
name: Verify
options:
  bundleIdPrefix: com.verify.xcfw.oc.swift
  deploymentTarget:
    iOS: "11.0"
  createIntermediateGroups: true
  projectFormat: xcode15_0
targets:
  VerifyApp:
    type: application
    platform: iOS
    sources:
      - path: src
    dependencies:
      - framework: ${xcframework}
        embed: true
    settings:
      base:
        PRODUCT_BUNDLE_IDENTIFIER: com.verify.xcfw.oc.swift.app
        GENERATE_INFOPLIST_FILE: "YES"
        SWIFT_VERSION: "5.9"
        TARGETED_DEVICE_FAMILY: "1,2"
        CODE_SIGNING_ALLOWED: "NO"
schemes:
  VerifyApp:
    build:
      targets:
        VerifyApp: all
YAML_EOF

  print_info "生成 Xcode 工程 (xcodegen) ..."
  (cd "${work_dir}" && xcodegen generate --quiet 2>/dev/null) || (cd "${work_dir}" && xcodegen generate)

  build_both "${work_dir}" "VerifyApp" "${work_dir}/build"
}

verify_xcframework_oc_oc_consumer() {
  print_step "xcframework · OC 版 → OC 消费者"

  local xcframework="${IOS_OC_DIR}/build/TencentQianWebView.xcframework"
  if [[ ! -d "${xcframework}" ]]; then
    echo -e "  ${YELLOW}⚠️  OC xcframework 不存在，先构建...${NC}"
    bash "${SCRIPT_DIR}/build-ios-objectivec.sh" xcframework
  fi
  if [[ ! -d "${xcframework}" ]]; then
    print_fail "OC xcframework 构建失败，跳过"
    TOTAL_COUNT=$((TOTAL_COUNT + 3))
    FAIL_COUNT=$((FAIL_COUNT + 3))
    return
  fi

  local work_dir="${TMP_BASE}/xcfw-oc-oc"
  mkdir -p "${work_dir}/src"

  cat > "${work_dir}/src/main.m" << 'OBJC_EOF'
#import <UIKit/UIKit.h>
#import <TencentQianWebView/TencentQianWebView.h>

@interface VerifyAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

@implementation VerifyAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [[UIViewController alloc] init];
    [self.window makeKeyAndVisible];
    return YES;
}
@end

int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, @"VerifyAppDelegate");
    }
}
OBJC_EOF

  cat > "${work_dir}/project.yml" << YAML_EOF
name: Verify
options:
  bundleIdPrefix: com.verify.xcfw.oc.oc
  deploymentTarget:
    iOS: "11.0"
  createIntermediateGroups: true
  projectFormat: xcode15_0
targets:
  VerifyApp:
    type: application
    platform: iOS
    sources:
      - path: src
    dependencies:
      - framework: ${xcframework}
        embed: true
    settings:
      base:
        PRODUCT_BUNDLE_IDENTIFIER: com.verify.xcfw.oc.oc.app
        GENERATE_INFOPLIST_FILE: "YES"
        CLANG_ENABLE_MODULES: "YES"
        CLANG_ENABLE_OBJC_ARC: "YES"
        TARGETED_DEVICE_FAMILY: "1,2"
        CODE_SIGNING_ALLOWED: "NO"
schemes:
  VerifyApp:
    build:
      targets:
        VerifyApp: all
YAML_EOF

  print_info "生成 Xcode 工程 (xcodegen) ..."
  (cd "${work_dir}" && xcodegen generate --quiet 2>/dev/null) || (cd "${work_dir}" && xcodegen generate)

  build_both "${work_dir}" "VerifyApp" "${work_dir}/build"
}

# ---- 汇总 --------------------------------------------------------------------
print_summary() {
  echo ""
  echo "═══════════════════════════════════════════════════════════════"
  echo -e "  验证汇总：${GREEN}${PASS_COUNT} PASS${NC} / ${RED}${FAIL_COUNT} FAIL${NC} / ${TOTAL_COUNT} TOTAL"
  echo "═══════════════════════════════════════════════════════════════"
  if [[ "${FAIL_COUNT}" -gt 0 ]]; then
    echo -e "  ${RED}❌ 有 ${FAIL_COUNT} 项验证失败，请检查上方日志。${NC}"
    exit 1
  else
    echo -e "  ${GREEN}✅ 全部验证通过！${NC}"
  fi
}

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

check_tools

target="${1:-all}"
case "${target}" in
  spm)
    verify_spm_swift
    verify_spm_oc_swift_consumer
    verify_spm_oc_oc_consumer
    ;;
  xcframework)
    verify_xcframework_swift
    verify_xcframework_oc_swift_consumer
    verify_xcframework_oc_oc_consumer
    ;;
  all)
    verify_spm_swift
    verify_spm_oc_swift_consumer
    verify_spm_oc_oc_consumer
    verify_xcframework_swift
    verify_xcframework_oc_swift_consumer
    verify_xcframework_oc_oc_consumer
    ;;
  *)
    echo "❌ 未知参数：${target}" >&2
    echo "用法：bash scripts/verify-ios-integration.sh [spm|xcframework|all]" >&2
    exit 1
    ;;
esac

print_summary
