platform :osx, '10.15'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def parse_KV_file(file, separator='=')
  file_abs_path = File.expand_path(file)
  if !File.exist? file_abs_path
    return [];
  end
  pods_ary = []
  skip_line_start_symbols = ["#", "/"]
  File.foreach(file_abs_path) { |line|
      next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
      plugin = line.split(pattern=separator)
      if plugin.length == 2
        podname = plugin[0].strip()
        path = plugin[1].strip()
        podpath = File.expand_path("#{path}", file_abs_path)
        pods_ary.push({:name => podname, :path => podpath});
      else
        puts "Invalid plugin specification: #{line}"
      end
  }
  return pods_ary
end

def pubspec_supports_macos(file)
  file_abs_path = File.expand_path(file)
  if !File.exist? file_abs_path
    return false;
  end
  File.foreach(file_abs_path) { |line|
    return true if line =~ /^\s*macos:/
  }
  return false
end

target 'Runner' do
  use_frameworks!
  use_modular_headers!

  # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock
  # referring to absolute paths on developers' machines.
  ephemeral_dir = File.join('Flutter', 'ephemeral')
  symlink_dir = File.join(ephemeral_dir, '.symlinks')
  symlink_plugins_dir = File.join(symlink_dir, 'plugins')
  system("rm -rf #{symlink_dir}")
  system("mkdir -p #{symlink_plugins_dir}")

  # Flutter Pods
  generated_xcconfig = parse_KV_file(File.join(ephemeral_dir, 'Flutter-Generated.xcconfig'))
  if generated_xcconfig.empty?
    puts "Flutter-Generated.xcconfig must exist. If you're running pod install manually, make sure flutter packages get is executed first."
  end
  generated_xcconfig.map { |p|
    if p[:name] == 'FLUTTER_FRAMEWORK_DIR'
      symlink = File.join(symlink_dir, 'flutter')
      File.symlink(File.dirname(p[:path]), symlink)
      pod 'FlutterMacOS', :path => File.join(symlink, File.basename(p[:path]))
    end
  }

  # Plugin Pods
  require 'json'
  plugin_dependencies_file = File.join('..', '.flutter-plugins-dependencies')
  if File.exist?(plugin_dependencies_file)
    plugin_dependencies = JSON.parse(File.read(plugin_dependencies_file))
    if plugin_dependencies['plugins'] && plugin_dependencies['plugins']['macos']
      plugin_dependencies['plugins']['macos'].each do |plugin|
        plugin_name = plugin['name']
        plugin_path = plugin['path']
        symlink = File.join(symlink_plugins_dir, plugin_name)
        File.symlink(plugin_path, symlink)
        if pubspec_supports_macos(File.join(symlink, 'pubspec.yaml'))
          pod plugin_name, :path => File.join(symlink, 'macos')
        end
      end
    end
  end
end

# Prevent Cocoapods from embedding a second Flutter framework and causing an error with the new Xcode build system.
install! 'cocoapods', :disable_input_output_paths => true

post_install do |installer|
  installer.pods_project.targets.each do |target|
    # Ensure Swift modules are properly configured
    if target.name == 'firebase_database'
      target.build_configurations.each do |config|
        config.build_settings['SWIFT_VERSION'] = '5.0'
        config.build_settings['DEFINES_MODULE'] = 'YES'
        config.build_settings['SWIFT_INCLUDE_PATHS'] = '$(PODS_TARGET_SRCROOT)/Sources'
      end
    end
    
    # Ensure firebase_core is properly configured for Swift import
    if target.name == 'firebase_core'
      target.build_configurations.each do |config|
        config.build_settings['DEFINES_MODULE'] = 'YES'
        config.build_settings['CLANG_ENABLE_MODULES'] = 'YES'
        config.build_settings['CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES'] = 'YES'
      end
    end
    
    # Ensure all targets have proper module configuration
    target.build_configurations.each do |config|
      config.build_settings['CLANG_ENABLE_MODULES'] = 'YES'
      config.build_settings['DEFINES_MODULE'] = 'YES'
    end
  end
end
