#!/usr/bin/env ruby

require 'find'
require 'fileutils'

path = '../../JUCE/modules/juce_gui_basics/'
output_path = 'melatonin/helpers/colour_ids.h'
FileUtils.mkdir_p('melatonin/helpers')
output_file = File.open(output_path, 'w')

script_name = File.basename($0)
current_date = Time.now.strftime("%Y-%m-%d")

output_file.write("// Generated by #{script_name} on #{current_date}\n")
output_file.write("// This file collects ColourIds from the JUCE GUI module by parsing the C++ files.\n")
output_file.write("#pragma once\n")
output_file.write("#include <juce_gui_basics/juce_gui_basics.h>\n\n")
output_file.write("namespace melatonin::colors\n{\n\n")

output_file.write("    struct ColourIdMapping\n    {\n        int value;\n        const char* name;\n    };\n\n")

output_file.write("    constexpr ColourIdMapping colourIdNames[] =\n    {\n")

Find.find(path) do |file|
  if File.file?(file)
    inside_enum = false
    file_name = File.basename(file)
    File.readlines(file).each_with_index do |line, line_number|
      if line.include?('enum ColourIds')
        inside_enum = true
      elsif inside_enum && line.strip.start_with?('}')
        inside_enum = false
      elsif inside_enum && line.include?('=')
        name, rest = line.strip.split('=')
        value, comment_part = rest.split(' ', 2)
        value.strip!
        value.chomp!(',') # Remove trailing comma if present
        comment = comment_part.to_s.split('*/').first.to_s.gsub('/**< ', '').strip
        cpp_map = "        { #{value}, \"#{name.strip}\" }, // #{file_name}:#{line_number + 1} #{comment}\n"
        output_file.write(cpp_map)
      end
    end
  end
end

output_file.write("    };\n\n} // namespace melatonin::colors\n")
output_file.close

puts "File written to #{output_path}"
