require "json"

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

# Single source of truth for the native iOS SDK version, shared with
# app.plugin.js (which builds the sdk-ios podspec URL from it). Hardcoding it
# here lets the two drift apart, which makes `pod install` unresolvable for
# every consumer - see issues #19 and #28.
didit_sdk_ios_version = package.dig("diditNativeSdkVersions", "ios").to_s
if didit_sdk_ios_version.empty?
  raise "Missing 'diditNativeSdkVersions.ios' in package.json - cannot pin the Didit iOS SDK."
end

legacy_nfc_enabled            = ENV.fetch("DIDIT_SDK_IOS_NFC_ENABLED",            "true").downcase != "false"
legacy_auto_detection_enabled = ENV.fetch("DIDIT_SDK_IOS_AUTO_DETECTION_ENABLED", "true").downcase != "false"
legacy_variant = case [legacy_nfc_enabled, legacy_auto_detection_enabled]
                 when [true,  true]  then "all"
                 when [false, true]  then "autodetection"
                 when [true,  false] then "nfc"
                 when [false, false] then "core"
                 end
didit_sdk_ios_variant = (
  defined?($DiditSdkIosVariant) && $DiditSdkIosVariant ?
    $DiditSdkIosVariant.to_s :
    ENV.fetch("DIDIT_SDK_IOS_VARIANT", legacy_variant)
).downcase

max_ios_version = lambda do |*versions|
  versions.map(&:to_s).max_by { |version| Gem::Version.new(version) }
end

didit_sdk_ios_min_version = ["all", "nfc"].include?(didit_sdk_ios_variant) ? max_ios_version.call(min_ios_version_supported, "15.0") : min_ios_version_supported

didit_sdk_subspec = case didit_sdk_ios_variant
                    when "all"           then "DiditSDK/All"
                    when "core"          then "DiditSDK/Core"
                    when "autodetection" then "DiditSDK/AutoDetection"
                    when "nfc"           then "DiditSDK/NFC"
                    else
                      raise "Invalid DiditSdk iOS variant '#{didit_sdk_ios_variant}'. Set $DiditSdkIosVariant or DIDIT_SDK_IOS_VARIANT to one of: all, core, autodetection, nfc."
                    end

# The sdk-ios SwiftPM products, one per variant. Same binaries as the
# CocoaPods subspecs above, resolved from the git tag instead of a raw podspec
# URL - see issue #27.
didit_sdk_spm_product = case didit_sdk_ios_variant
                        when "all"           then "DiditSDK"
                        when "core"          then "DiditSDKCore"
                        when "autodetection" then "DiditSDKAutoDetection"
                        when "nfc"           then "DiditSDKNFC"
                        end

# How the native SDK is resolved: "spm" pulls it straight from the sdk-ios
# repo via SwiftPM, so consumers need no `pod 'DiditSDK', :podspec => ...` line
# at all. "cocoapods" (default) keeps the existing raw-podspec flow.
didit_sdk_ios_linkage = (
  defined?($DiditSdkIosLinkage) && $DiditSdkIosLinkage ?
    $DiditSdkIosLinkage.to_s :
    ENV.fetch("DIDIT_SDK_IOS_LINKAGE", "cocoapods")
).downcase

unless ["spm", "cocoapods"].include?(didit_sdk_ios_linkage)
  raise "Invalid DiditSdk iOS linkage '#{didit_sdk_ios_linkage}'. Set $DiditSdkIosLinkage or DIDIT_SDK_IOS_LINKAGE to one of: spm, cocoapods."
end

# `spm_dependency` ships with React Native 0.75+. Falling back silently would
# leave the consumer with no DiditSDK at all (they removed the pod line), so
# fail loudly instead.
if didit_sdk_ios_linkage == "spm" && !defined?(spm_dependency)
  raise "DiditSdk iOS linkage 'spm' requires React Native 0.75 or newer (spm_dependency is unavailable). Use the 'cocoapods' linkage instead."
end

Pod::Spec.new do |s|
  s.name         = "SdkReactNative"
  s.version      = package["version"]
  s.summary      = package["description"]
  s.homepage     = package["homepage"]
  s.license      = package["license"]
  s.authors      = package["author"]

  s.platforms    = { :ios => didit_sdk_ios_min_version }
  s.source       = { :git => "https://github.com/didit-protocol/sdk-react-native.git", :tag => "#{s.version}" }

  s.source_files = "ios/**/*.{h,m,mm,swift,cpp}"
  s.private_header_files = "ios/**/*.h"

  s.static_framework = true
  s.swift_version    = "5.0"

  s.pod_target_xcconfig = {
    "FRAMEWORK_SEARCH_PATHS" => [
      '$(inherited)',
      '"${PODS_CONFIGURATION_BUILD_DIR}/DiditSDK"',
      '"${PODS_XCFRAMEWORKS_BUILD_DIR}/DiditSDK"',
      '"${PODS_XCFRAMEWORKS_BUILD_DIR}/DiditSDK/All"',
      '"${PODS_XCFRAMEWORKS_BUILD_DIR}/DiditSDK/Core"',
      '"${PODS_XCFRAMEWORKS_BUILD_DIR}/DiditSDK/AutoDetection"',
      '"${PODS_XCFRAMEWORKS_BUILD_DIR}/DiditSDK/NFC"'
    ].join(" ")
  }

  if didit_sdk_ios_linkage == "spm"
    spm_dependency(s,
      url: "https://github.com/didit-protocol/sdk-ios.git",
      requirement: { kind: "exactVersion", version: didit_sdk_ios_version },
      products: [didit_sdk_spm_product]
    )
  else
    s.dependency didit_sdk_subspec, didit_sdk_ios_version
  end

  install_modules_dependencies(s)
end
