# Resolve react_native_pods.rb with node to allow for hoisting
require Pod::Executable.execute_command('node', ['-p',
  'require.resolve(
    "react-native/scripts/react_native_pods.rb",
    {paths: [process.argv[1]]},
  )', __dir__]).strip

# Paper 旧架构（海外 legacy 对拍 RN 0.73 + AGP 8）
ENV['RCT_NEW_ARCH_ENABLED'] = '0'
ENV['NO_FLIPPER'] = '1'

platform :ios, min_ios_version_supported
prepare_react_native_project!

flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled

linkage = ENV['USE_FRAMEWORKS']
if linkage != nil
  Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
  use_frameworks! :linkage => linkage.to_sym
end

target 'ReactNativeSdkExampleLegacy' do
  config = use_native_modules!

  use_react_native!(
    :path => config[:reactNativePath],
    :flipper_configuration => flipper_config,
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 'ReactNativeSdkExampleLegacyTests' do
    inherit! :complete
  end

  post_install do |installer|
    react_native_post_install(
      installer,
      config[:reactNativePath],
      :mac_catalyst_enabled => false
    )

    strip_ld_classic = lambda do |cfg|
      ldflags = cfg.build_settings['OTHER_LDFLAGS']
      if ldflags.is_a?(Array)
        cfg.build_settings['OTHER_LDFLAGS'] = ldflags
          .reject { |f| f.to_s.include?('ld_classic') }
          .map { |f| f == '$(inherited)-Wl' ? '$(inherited)' : f }
          .reject { |f| f.to_s.strip.empty? || f.to_s.strip == '-Wl' }
      elsif ldflags.is_a?(String)
        cfg.build_settings['OTHER_LDFLAGS'] = ldflags
          .gsub(/-Wl?\s*-ld_classic\s*/, ' ')
          .gsub('$(inherited)-Wl', '$(inherited)')
          .strip
      end
    end

    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |cfg|
        flags = cfg.build_settings['OTHER_CPLUSPLUSFLAGS'] || '$(inherited)'
        unless flags.to_s.include?('deprecated-literal-operator')
          cfg.build_settings['OTHER_CPLUSPLUSFLAGS'] = "#{flags} -Wno-error=deprecated-literal-operator"
        end
        strip_ld_classic.call(cfg)
      end
    end

    installer.aggregate_targets.map(&:user_project).uniq.each do |project|
      project.build_configurations.each { |cfg| strip_ld_classic.call(cfg) }
      project.targets.each do |target|
        target.build_configurations.each { |cfg| strip_ld_classic.call(cfg) }
      end
      project.save
    end
  end
end
