platform :ios, '16.0'

target 'suixinkan' do
  use_frameworks!

  # 高德地图 SDK：仅真机构建时链接；模拟器通过 post_install 剥离（见下方说明）
  pod 'AMap3DMap-NO-IDFA', '~> 11.1'
  pod 'AMapSearch-NO-IDFA', '~> 9.7'
  pod 'AMapLocation-NO-IDFA', '~> 2.11'

  # 微信 Open SDK：分享能力（不调用支付 API）
  pod 'WechatOpenSDK-XCFramework', '~> 2.0.4'

  # 友盟 SDK：统计分析与应用性能监控，初始化需等用户同意隐私政策后再触发
  pod 'UMCommon'
  pod 'UMDevice'
  pod 'UMAPM'

  target 'suixinkanTests' do
    inherit! :search_paths
  end
end

AMAP_SIMULATOR_FRAMEWORK_NAMES = %w[
  AMapFoundationKit
  AMapLocationKit
  AMapSearchKit
  MAMapKit
].freeze

def other_ldflags_without_amap(other_ldflags)
  stripped = other_ldflags.dup

  AMAP_SIMULATOR_FRAMEWORK_NAMES.each do |framework_name|
    stripped = stripped.gsub(/ -framework "#{Regexp.escape(framework_name)}"/, '')
  end
  stripped
end

post_install do |installer|
  # 1. 修正 aggregate xcconfig：去掉 arm64 排除，模拟器单独链接（不链 AMap）
  %w[Pods-suixinkan Pods-suixinkanTests].each do |target_name|
    support_dir = File.join(installer.sandbox.root, 'Target Support Files', target_name)
    Dir.glob(File.join(support_dir, '*.xcconfig')).each do |path|
      content = File.read(path)
      content.gsub!("EXCLUDED_ARCHS[sdk=iphonesimulator*] = arm64\n", '')

      # 模拟器剥离高德 framework，但保留 CocoaPods 生成的微信、友盟和其他依赖链接参数。
      # 真机条件下再补回完整链接参数，避免真机能力受影响。
      if (device_ldflags = content[/^OTHER_LDFLAGS = (.*)$/, 1])
        simulator_ldflags = other_ldflags_without_amap(device_ldflags)
        content.gsub!(/^OTHER_LDFLAGS = .*\n/, "OTHER_LDFLAGS = #{simulator_ldflags}\n")
        content.gsub!(/OTHER_LDFLAGS\[sdk=iphonesimulator\*\] = .*\n/, '')
        content.gsub!(/OTHER_LDFLAGS\[sdk=iphoneos\*\] = .*\n/, '')
        content << "\nOTHER_LDFLAGS[sdk=iphoneos*] = #{device_ldflags}\n"
      end

      File.write(path, content)
    end
  end

  # 2. AMap pod target 标记为仅真机
  installer.pods_project.targets.each do |target|
    next unless target.name.start_with?('AMap')

    target.build_configurations.each do |config|
      config.build_settings['SUPPORTED_PLATFORMS'] = 'iphoneos'
    end
  end

  # 3. 模拟器跳过 AMap.bundle 资源拷贝（当前 Pods 资源仅此一项）
  resources_script = File.join(
    installer.sandbox.root,
    'Target Support Files/Pods-suixinkan/Pods-suixinkan-resources.sh'
  )
  if File.exist?(resources_script)
    content = File.read(resources_script)
    unless content.include?('SKIP_AMAP_RESOURCES_FOR_SIMULATOR')
      content.sub!(
        "RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt",
        <<~SHELL
          # SKIP_AMAP_RESOURCES_FOR_SIMULATOR
          if [ "${EFFECTIVE_PLATFORM_NAME}" = "-iphonesimulator" ]; then
            exit 0
          fi

          RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt
        SHELL
      )
      File.write(resources_script, content)
    end
  end

  # 4. 主工程：允许 arm64 模拟器、真机编译期注入 AMAP_ENABLED、关闭脚本沙盒（CocoaPods 兼容）
  installer.aggregate_targets.each do |aggregate_target|
    aggregate_target.user_project.native_targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = ''
        config.build_settings['ENABLE_USER_SCRIPT_SANDBOXING'] = 'NO'

        next unless target.name == 'suixinkan'

        existing = config.build_settings['SWIFT_ACTIVE_COMPILATION_CONDITIONS[sdk=iphoneos*]'] || '$(inherited)'
        config.build_settings['SWIFT_ACTIVE_COMPILATION_CONDITIONS[sdk=iphoneos*]'] = "#{existing} AMAP_ENABLED" unless existing.to_s.include?('AMAP_ENABLED')
      end
    end
    aggregate_target.user_project.save
  end
end
