#!/usr/bin/env ruby
require 'xcodeproj'

# Open the project
project_path = 'lichunWebsocket.xcodeproj'
project = Xcodeproj::Project.open(project_path)

# Get the main target
target = project.targets.first

# List of file names to look for
file_names = ['LiquidGlassTabBar.swift', 'LiquidGlassTabContainer.swift', 'QuickActionsMenu.swift', 'SocialView.swift']

# Remove ALL references to these files
puts "Removing all existing references..."
target.source_build_phase.files.to_a.reverse_each do |build_file|
  if build_file.file_ref && file_names.any? { |name| build_file.file_ref.path&.include?(name) }
    puts "Removing: #{build_file.file_ref.path}"
    build_file.remove_from_project
  end
end

# Also remove file references from the project
project.main_group.recursive_children.select { |child| child.is_a?(Xcodeproj::Project::Object::PBXFileReference) }.each do |file_ref|
  if file_names.any? { |name| file_ref.path&.include?(name) }
    puts "Removing file ref: #{file_ref.path}"
    file_ref.remove_from_project
  end
end

# Remove empty groups
['Navigation', 'Social'].each do |group_name|
  project.main_group.recursive_children.select { |child| child.is_a?(Xcodeproj::Project::Object::PBXGroup) && child.name == group_name }.each do |group|
    if group.children.empty?
      puts "Removing empty group: #{group_name}"
      group.remove_from_project
    end
  end
end

puts "\nAdding files with correct paths..."

# Find the correct groups
main_group = project.main_group['lichunWebsocket']
shared_group = main_group['Shared']
components_group = shared_group['Components']
features_group = main_group['Features']

# Create Navigation group
navigation_group = components_group.new_group('Navigation', 'Shared/Components/Navigation')

# Add Navigation files
['LiquidGlassTabBar.swift', 'LiquidGlassTabContainer.swift', 'QuickActionsMenu.swift'].each do |filename|
  file_ref = navigation_group.new_reference(filename)
  file_ref.source_tree = '<group>'
  target.add_file_references([file_ref])
  puts "Added: #{filename} to Navigation group"
end

# Create Social group
social_group = features_group.new_group('Social', 'Features/Social')

# Add Social file
file_ref = social_group.new_reference('SocialView.swift')
file_ref.source_tree = '<group>'
target.add_file_references([file_ref])
puts "Added: SocialView.swift to Social group"

# Save the project
project.save

puts "\nFiles cleaned and added successfully!"
