require 'pathname'

require 'json'
podfile_properties = JSON.parse(File.read('./Podfile.properties.json')) rescue {}
showDevWindow = podfile_properties['showDevWindow'] == 'true'
showDockIcon = podfile_properties['showDockIcon'] == 'true'
other_cflags = "$(inherited) "+ (showDevWindow ? " -D"+"SHOW_DEV_WINDOW" : "") + (showDockIcon ? " -D"+"SHOW_DOCK_ICON" : "")

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

relative_rn_macos_path = ''

# Delete the codegen build folder
FileUtils.remove_dir("./build", true)

prepare_react_native_project!

target 'ExpoMenuBar-macOS' do
  platform :macos, '14.0'
  use_expo_modules!
  config_command = [
    'npx',
    'expo-modules-autolinking',
    'react-native-config',
    '--json',
    '--platform',
    'macos',
    '--source-dir',
    File.expand_path('.', __dir__)
  ]
  config = use_native_modules!(config_command)

  relative_rn_macos_path = "#{config[:reactNativePath]}"
  use_react_native!(
    :path => relative_rn_macos_path,
    :hermes_enabled => true
  )

  # Pods specifically for macOS target
  pod 'Swifter', '~> 1.5.0'
end

use_frameworks! :linkage => :static

post_install do |installer|
  react_native_post_install(installer, relative_rn_macos_path)

  installer.pods_project.targets.each do |target|
    # TODO: remove this when bumping react-native-macos
    if target.name == 'fmt'
      target.build_configurations.each do |config|
        config.build_settings['CLANG_CXX_LANGUAGE_STANDARD'] = 'c++17'
      end
    end
    # Xcode 27 only supports macOS deployment targets >= 12.0, but some pods
    # TODO: investigate which pods still declare old deployment targets
    target.build_configurations.each do |config|
      if config.build_settings['MACOSX_DEPLOYMENT_TARGET'].to_f < 12.0
        config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '12.0'
      end
    end
  end

  project = installer.generated_aggregate_targets.first.user_project
  project.targets.each do |target|
    if target.name == 'ExpoMenuBar-macOS'
      target.build_configurations.each do |config|
        config.build_settings['OTHER_CFLAGS'] = other_cflags
      end
    end
  end

  project.save
end
