require "json"

package = JSON.parse(File.read(File.join(__dir__, "package.json")))
folly_compiler_flags = '-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1 -Wno-comma -Wno-shorten-64-to-32'

# To release a new SDK version, change this number only (it must be a tag of PaygilantSDK-SPM).
paygilant_sdk_version = "4.2.5"

# Downloads and checksum-verifies PaygilantSDK.xcframework into ios/ unless that version is already there.
# Done here (not in `prepare_command`) because CocoaPods does not run prepare_command for :path pods,
# which is how React Native autolinking installs this pod from node_modules.
paygilant_fetch_sdk_xcframework = lambda do |root, version|
  require "digest"
  require "fileutils"
  require "tmpdir"

  ios_dir = File.join(root, "ios")
  xcframework = File.join(ios_dir, "PaygilantSDK.xcframework")
  marker = File.join(ios_dir, ".paygilant_sdk_version")
  next if File.directory?(xcframework) && File.exist?(marker) && File.read(marker).strip == version

  manifest_url = "https://raw.githubusercontent.com/Paygilant/PaygilantSDK-SPM/#{version}/Package.swift"
  manifest = `curl -fsSL --retry 3 --connect-timeout 20 "#{manifest_url}"`
  url = manifest[/url:\s*"([^"]+\.zip)"/, 1]
  checksum = manifest[/checksum:\s*"([0-9a-fA-F]{64})"/, 1]
  if !$?.success? || url.nil? || checksum.nil?
    raise "[Paygilant] Could not read the SDK url/checksum for #{version} from #{manifest_url}"
  end

  Dir.mktmpdir("paygilant-sdk") do |tmp|
    zip = File.join(tmp, "PaygilantSDK.xcframework.zip")
    Pod::UI.puts "[Paygilant] Downloading PaygilantSDK #{version}"
    raise "[Paygilant] Download failed: #{url}" unless system("curl", "-fsSL", "--retry", "3", "--connect-timeout", "20", "-o", zip, url)
    actual = Digest::SHA256.file(zip).hexdigest
    raise "[Paygilant] Checksum mismatch for #{version}: expected #{checksum}, got #{actual}" unless actual.casecmp(checksum).zero?
    raise "[Paygilant] Could not unzip the SDK" unless system("unzip", "-q", "-o", zip, "-d", tmp, "-x", "__MACOSX/*")
    FileUtils.rm_rf(xcframework)
    FileUtils.mv(File.join(tmp, "PaygilantSDK.xcframework"), xcframework)
  end
  File.write(marker, version)
end

paygilant_fetch_sdk_xcframework.call(__dir__, paygilant_sdk_version)

Pod::Spec.new do |s|
  s.name         = "react-native-paygilant-wrapper"
  s.version      = package["version"]
  s.summary      = package["description"]
  s.homepage     = package["homepage"]
  s.license      = package["license"]
  s.authors      = package["author"]

  s.platforms    = { :ios => "12.0" }
  s.source       = { :git => "https://github.com/Paygilant/react-native-wrapper.git", :tag => "#{s.version}" }

  s.source_files = "ios/**/*.{h,m,mm,swift}"
  # The downloaded SDK lives under ios/; keep its headers/modules out of this pod's own sources.
  s.exclude_files = "ios/PaygilantSDK.xcframework/**/*"
  s.requires_arc = true

  # CocoaPods trunk goes read-only on 2026-12-02 (PG-6399), so the SDK is no longer a pod
  # dependency. The prebuilt xcframework is fetched from the PaygilantSDK-SPM release for this
  # version (URL + checksum come from its Package.swift) and vendored into this pod.
  s.vendored_frameworks = "ios/PaygilantSDK.xcframework"
  # With use_frameworks! :linkage => :dynamic this pod is a framework and must link the SDK itself.
  s.pod_target_xcconfig = { "OTHER_LDFLAGS" => "$(inherited) -framework PaygilantSDK" }

  # Use install_modules_dependencies helper to install the dependencies if React Native version >=0.71.0.
  # See https://github.com/facebook/react-native/blob/febf6b7f33fdb4904669f99d795eba4c0f95d7bf/scripts/cocoapods/new_architecture.rb#L79.
  if respond_to?(:install_modules_dependencies, true)
    install_modules_dependencies(s)
  else
  s.dependency "React-Core"
  # Don't install the dependencies when we run `pod install` in the old architecture.
  if ENV['RCT_NEW_ARCH_ENABLED'] == '1' then
    s.compiler_flags = folly_compiler_flags + " -DRCT_NEW_ARCH_ENABLED=1"
    s.pod_target_xcconfig    = {
        "HEADER_SEARCH_PATHS" => "\"$(PODS_ROOT)/boost\"",
        "OTHER_CPLUSPLUSFLAGS" => "-DFOLLY_NO_CONFIG -DFOLLY_MOBILE=1 -DFOLLY_USE_LIBCPP=1",
        "CLANG_CXX_LANGUAGE_STANDARD" => "c++17"
    }
    s.dependency "React-Codegen"
    s.dependency "RCT-Folly"
    s.dependency "RCTRequired"
    s.dependency "RCTTypeSafety"
    s.dependency "ReactCommon/turbomodule/core"
   end
  end    
end
