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")

# ORBIT_HERMES_CLI=1 (or "hermesCli": "true" in Podfile.properties.json)
# opts into running the CLI on the app's own Hermes through hermes-node
# instead of the pkg-built Node binaries. Hermes then comes from the
# facebook/hermes commit that hermes-node pins, so the app and the CLI share
# one engine and the CLI can link the app's hermesvm.framework. It is
# downloaded prebuilt when published for this checkout
# (scripts/hermes-prebuilt.sh; the "Select Hermes flavor" build phase switches
# between the Debug and Release builds) and built from source otherwise
# (scripts/hermes-node.sh). Either way its JSI replaces React Native's
# (scripts/vendor-jsi.sh).
hermes_cli = ENV['ORBIT_HERMES_CLI'] == '1' || podfile_properties['hermesCli'] == 'true'
if hermes_cli
  ENV['RCT_HERMES_V1_ENABLED'] = '1'
  unless ENV['HERMES_ENGINE_TARBALL_PATH'] || ENV['REACT_NATIVE_OVERRIDE_HERMES_DIR']
    prebuilt_dir = `"#{__dir__}/scripts/hermes-prebuilt.sh" fetch`.strip
    if $?.success? && !prebuilt_dir.empty?
      ENV['HERMES_ENGINE_TARBALL_PATH'] = File.join(prebuilt_dir, 'hermes-engine-macos-debug.tar.gz')
      hermes_jsi_dir = File.join(prebuilt_dir, 'jsi')
    else
      hermes_dir = `"#{__dir__}/scripts/hermes-node.sh" fetch`.strip
      raise 'scripts/hermes-node.sh fetch failed' unless $?.success? && !hermes_dir.empty?
      ENV['REACT_NATIVE_OVERRIDE_HERMES_DIR'] = hermes_dir
      hermes_jsi_dir = File.join(hermes_dir, 'API', 'jsi', 'jsi')
    end
    # React Native has to compile against the JSI this Hermes was built with.
    system(File.join(__dir__, 'scripts', 'vendor-jsi.sh'), hermes_jsi_dir) || raise('scripts/vendor-jsi.sh failed')
  end
else
  system(File.join(__dir__, 'scripts', 'vendor-jsi.sh'), '--restore') || raise('scripts/vendor-jsi.sh failed')
end

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 = [
    'node',
    '--no-warnings',
    '--eval',
    'require(\'expo/bin/autolinking\')',
    '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)

  # Tells the Build CLI and Select Hermes flavor phases which CLI to build.
  hermes_cli_marker = File.join(installer.sandbox.root.to_s, '.orbit-hermes-cli')
  hermes_cli ? FileUtils.touch(hermes_cli_marker) : FileUtils.rm_f(hermes_cli_marker)

  installer.pods_project.targets.each do |target|
    # Fail before anything compiles against React Native's own JSI if a yarn
    # install replaced the copy pod install vendored (scripts/vendor-jsi.sh).
    if hermes_cli && target.name == 'React-jsi'
      phase = target.new_shell_script_build_phase('[Orbit] Check vendored JSI')
      phase.shell_script = "\"$PODS_ROOT/../scripts/vendor-jsi.sh\" --check\n"
      phase.always_out_of_date = '1'
      target.build_phases.delete(phase)
      target.build_phases.unshift(phase)
    end
    # 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
