require File.join(File.dirname(`node --print "require.resolve('expo/package.json')"`), "scripts/autolinking")
require File.join(File.dirname(`node --print "require.resolve('react-native/package.json')"`), "scripts/react_native_pods")

require 'json'
podfile_properties = JSON.parse(File.read(File.join(__dir__, 'Podfile.properties.json'))) rescue {}

ENV['EX_DEV_CLIENT_NETWORK_INSPECTOR'] ||= podfile_properties['EX_DEV_CLIENT_NETWORK_INSPECTOR']
ENV['RCT_USE_RN_DEP'] ||= '1' if podfile_properties['ios.buildReactNativeFromSource'] != 'true'

# Do not change this otherwise reanimated will have less performance 
# see: https://docs.swmansion.com/react-native-reanimated/docs/guides/feature-flags/#disable_commit_pausing_mechanism
ENV['RCT_USE_PREBUILT_RNCORE'] = '0'

ENV['RCT_HERMES_V1_ENABLED'] ||= '1' if podfile_properties['expo.useHermesV1'] == 'true'

def node_require(script)
  # Resolve script with node to allow for hoisting
  require Pod::Executable.execute_command('node', ['-p',
    "require.resolve(
      '#{script}',
      {paths: [process.argv[1]]},
    )", __dir__]).strip
end

source 'https://github.com/CocoaPods/Specs.git'

# Use it to require both react-native's and this package's scripts:
node_require('react-native/scripts/react_native_pods.rb')
node_require('react-native-permissions/scripts/setup.rb')

platform :ios, '15.5'
install! 'cocoapods', :disable_input_output_paths => true, :deterministic_uuids => false

prepare_react_native_project!

setup_permissions([
  'Camera',
  'Microphone',
  'PhotoLibrary',
  'Notifications',
])

# Fix to solve: 'error: Multiple commands produce GoogleUtilities.framework'
def google_utilities
  pod 'GoogleUtilities', '8.1.0'
  pod 'GTMSessionFetcher'
end

target 'humand' do
  use_expo_modules!

  pod 'RNTextSize', :path => '../node_modules/react-native-text-size/ios'

  # MMKV Core for native Swift usage (shared storage with react-native-mmkv)
  pod 'MMKV', '~> 2.0'

  pod 'StreamVideo', '~> 1.46.0'

  google_utilities

  # GoogleMLKit added directly (removed from VisionCameraFaceDetector podspec
  # to prevent EXCLUDED_ARCHS propagation that blocks arm64 simulator builds).
  # The Swift code in VisionCameraFaceDetector uses #if !targetEnvironment(simulator)
  # guards so MLKit is only used on real devices.
  pod 'GoogleMLKit/FaceDetection', '7.0.0'

  if ENV['EXPO_USE_COMMUNITY_AUTOLINKING'] == '1'
    config_command = ['node', '-e', "process.argv=['', '', 'config'];require('@react-native-community/cli').run()"];
  else
    config_command = [
      'npx',
      'expo-modules-autolinking',
      'react-native-config',
      '--json',
      '--platform',
      'ios'
    ]
  end

  config = use_native_modules!(config_command)

  use_frameworks! :linkage => :static
  $RNFirebaseAsStaticFramework = true
  $RNFirebaseAnalyticsWithoutAdIdSupport=true

  use_react_native!(
    :path => config[:reactNativePath],
    :hermes_enabled => podfile_properties['expo.jsEngine'] == nil || podfile_properties['expo.jsEngine'] == 'hermes',
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/..",
    :privacy_file_aggregation_enabled => podfile_properties['apple.privacyManifestAggregationEnabled'] != 'false',
  )

  pre_install do |installer|
    installer.pod_targets.each do |pod|
      if pod.name.eql?('op-sqlite')
        def pod.build_type
          Pod::BuildType.static_library
        end
      end
    end
  end

  post_install do |installer|
    node_path = `which node`.strip
    installer.pods_project.targets.each do |t|
      t.build_configurations.each do |cfg|
        cfg.build_settings['NODE_BINARY'] = node_path
      end
    end

    react_native_post_install(
      installer,
      config[:reactNativePath],
      :mac_catalyst_enabled => true,
      :ccache_enabled => podfile_properties['apple.ccacheEnabled'] == 'true',
    )

    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        # Only build the active architectures
        config.build_settings["ONLY_ACTIVE_ARCH"] = "YES"
        # Fix warnings treated as errors with New Architecture
        config.build_settings['GCC_TREAT_WARNINGS_AS_ERRORS'] = 'NO'
        # Allow non-modular includes in framework modules
        config.build_settings['CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES'] = 'YES'
        # Disable code signing for Apple Auth bundle
        if target.respond_to?(:product_type) and target.product_type == "com.apple.product-type.bundle"
          config.build_settings['CODE_SIGNING_ALLOWED'] = 'NO'
        end

      end
    end

    configure_mlkit_for_arm64_simulator(installer)
  end
end

target 'ImageNotification' do
  google_utilities

  use_frameworks! :linkage => :static

  pod 'Firebase/Messaging'
  pod 'MMKV', '~> 2.0'
  # Is needed for KEYCHAIN_KEY access
  pod 'OpenSSL-Universal'
end

def configure_mlkit_for_arm64_simulator(installer)
  # GoogleMLKit doesn't support arm64 simulators. We handle this in Swift code
  # with #if !targetEnvironment(simulator) guards, but we also need to prevent
  # the linker from trying to link MLKit frameworks on simulator builds.
  # Strategy: remove MLKit from base xcconfig settings (used by simulator),
  # and re-add MLKit only for device via [sdk=iphoneos*] overrides.
  mlkit_pods = %w[MLImage MLKitCommon MLKitFaceDetection MLKitVision GoogleMLKit]

  installer.aggregate_targets.each do |aggregate_target|
    aggregate_target.xcconfigs.each do |config_name, xcconfig|
      # Remove EXCLUDED_ARCHS propagated by MLKit's user_target_xcconfig
      xcconfig.attributes.delete('EXCLUDED_ARCHS[sdk=iphonesimulator*]')

      # Strip MLKit from FRAMEWORK_SEARCH_PATHS and re-add for device only
      if fsp = xcconfig.attributes['FRAMEWORK_SEARCH_PATHS']
        mlkit_fsp = fsp.split(' ').select { |path| mlkit_pods.any? { |pod| path.include?(pod) } }
        base_fsp = fsp.split(' ').reject { |path| mlkit_pods.any? { |pod| path.include?(pod) } }
        xcconfig.attributes['FRAMEWORK_SEARCH_PATHS'] = base_fsp.join(' ')
        xcconfig.attributes['FRAMEWORK_SEARCH_PATHS[sdk=iphoneos*]'] = "$(inherited) #{mlkit_fsp.join(' ')}"
      end

      # Strip MLKit from HEADER_SEARCH_PATHS and re-add for device only
      if hsp = xcconfig.attributes['HEADER_SEARCH_PATHS']
        mlkit_hsp = hsp.split(' ').select { |path| mlkit_pods.any? { |pod| path.include?(pod) } }
        base_hsp = hsp.split(' ').reject { |path| mlkit_pods.any? { |pod| path.include?(pod) } }
        xcconfig.attributes['HEADER_SEARCH_PATHS'] = base_hsp.join(' ')
        xcconfig.attributes['HEADER_SEARCH_PATHS[sdk=iphoneos*]'] = "$(inherited) #{mlkit_hsp.join(' ')}"
      end

      xcconfig_path = aggregate_target.xcconfig_path(config_name)
      xcconfig.save_as(xcconfig_path)

      # OTHER_LDFLAGS is managed by CocoaPods internally (not in xcconfig.attributes).
      # Post-process the file: strip MLKit from base OTHER_LDFLAGS and add them
      # back only for device via OTHER_LDFLAGS[sdk=iphoneos*].
      file_content = File.read(xcconfig_path)
      file_content.lines.each do |line|
        next unless line.start_with?('OTHER_LDFLAGS =')

        tokens = line.chomp.sub('OTHER_LDFLAGS = ', '').split(' ')
        base_tokens = []
        mlkit_tokens = []
        skip_next = false

        tokens.each_with_index do |token, i|
          if skip_next
            skip_next = false
            next
          end

          is_mlkit = token == '-framework' && i + 1 < tokens.length &&
            mlkit_pods.any? { |pod| tokens[i + 1].tr('"', '').start_with?(pod) }
          is_mlkit_standalone = mlkit_pods.any? { |pod| token.tr('"', '').start_with?(pod) }

          if is_mlkit
            mlkit_tokens << token << tokens[i + 1]
            skip_next = true
          elsif is_mlkit_standalone
            mlkit_tokens << token
          else
            base_tokens << token
          end
        end

        # Rewrite with MLKit stripped from base, added to device-only
        new_content = file_content.sub(line, "OTHER_LDFLAGS = #{base_tokens.join(' ')}\n")
        new_content += "OTHER_LDFLAGS[sdk=iphoneos*] = $(inherited) #{mlkit_tokens.join(' ')}\n"
        file_content = new_content
        break
      end

      File.write(xcconfig_path, file_content)
    end
  end
end
