require "json"
package = JSON.parse(File.read(File.join(__dir__, "package.json")))

is_new_arch_enabled = ENV["RCT_NEW_ARCH_ENABLED"] == "1"
folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -DFOLLY_CFG_NO_COROUTINES=1 -Wno-comma -Wno-shorten-64-to-32'
Pod::Spec.new do |s|
  # Basic metadata
  s.name         = 'ContentsquareBridgeModule'
  s.version      = package["version"]
  s.summary      = package["description"]
  s.description  = 'ContentsquareBridgeModule'
  s.homepage     = 'https://www.contentsquare.com'
  s.license      = "MIT"
  s.author       = { 'Romain Bouic' => 'romain.bouic@contentsquare.com' }

  # Source configuration
  s.platform     = :ios, '12.4'
  s.source       = { :git => "https://github.com/ContentSquare/cs-react-native-sdk.git", :tag => "#{s.version}" }

  # 👇 Base configuration that always applies
  base_config = { "DEFINES_MODULE" => "YES" }

  s.dependency 'ContentsquareSDK', '1.6.3'

  s.source_files = "ios/**/*.{h,m,mm,swift}"
  s.exclude_files = "ios/Pods"

  # Build configuration
  s.requires_arc = true
  s.static_framework = true

  # Dependencies

  # React Native architecture handling
  if defined?(install_modules_dependencies()) != nil
    install_modules_dependencies(s)
    if is_new_arch_enabled then
      s.compiler_flags = folly_compiler_flags
      s.pod_target_xcconfig = base_config.merge({
        "OTHER_CPLUSPLUSFLAGS" => "-DRCT_NEW_ARCH_ENABLED=1",
        "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\" \"$(PODS_ROOT)/Headers/Private/Yoga\" \"$(PODS_ROOT)/../../node_modules/react-native/ReactCommon\" \"$(PODS_ROOT)/../../node_modules/react-native/ReactCommon/react/renderer/components/text/platform/cxx\"",
        "CLANG_CXX_LANGUAGE_STANDARD" => "c++17",
      })
    else
      s.pod_target_xcconfig = base_config
    end
  else
    if is_new_arch_enabled then
      s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
      s.pod_target_xcconfig = base_config.merge({
        "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
        "CLANG_CXX_LANGUAGE_STANDARD" => "c++17",
        "OTHER_CPLUSPLUSFLAGS" => "-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1",
      })

      s.dependency "React-RCTFabric"
      s.dependency "React-Codegen"
      s.dependency "RCT-Folly"
      s.dependency "RCTRequired"
      s.dependency "RCTTypeSafety"
      s.dependency "ReactCommon/turbomodule/core"
    else
      # Legacy architecture
      s.dependency 'React-Core'
      s.compiler_flags = folly_compiler_flags
      s.pod_target_xcconfig = base_config
    end
  end

end
