#!/usr/bin/env ruby
# Add SpeechEnginePlugin.h/m to the Runner target if not already present.
# Run with: ruby ios/scripts/add_speech_plugin.rb

require 'xcodeproj'

project_path = File.expand_path('../Runner.xcodeproj', __dir__)
project = Xcodeproj::Project.open(project_path)

runner_group = project.main_group['Runner']
abort('Runner group not found in pbxproj') unless runner_group

runner_target = project.targets.find { |t| t.name == 'Runner' }
abort('Runner target not found in pbxproj') unless runner_target

%w[SpeechEnginePlugin.h SpeechEnginePlugin.m].each do |name|
  abs_path = File.expand_path("../Runner/#{name}", __dir__)
  unless File.exist?(abs_path)
    warn "Skipping #{name} (file not found at #{abs_path})"
    next
  end

  existing_ref = runner_group.files.find { |f| f.path == name }
  file_ref = existing_ref || runner_group.new_reference(name)

  if name.end_with?('.m')
    already_in_build = runner_target.source_build_phase.files_references.include?(file_ref)
    runner_target.add_file_references([file_ref]) unless already_in_build
  end

  puts "✓ #{name} #{existing_ref ? 'already referenced' : 'added'} in Runner target"
end

project.save
puts "✓ Xcode project saved"
