# frozen_string_literal: true

desc <<-TXT
  Finds Unicode properties supported by both Ruby and ES2018+, filters out those
  that match the same character set in both languages, and writes a file mapping
  normalized, Ruby-compatible property names to ES-compatible property names.
TXT
task :build_prop_map do
  require 'regexp_property_values'
  require 'mini_racer'
  require 'character_set'

  js_context = MiniRacer::Context.new

  # prepare string with all codepoints for matching behavior tests
  js_context.eval <<-JS
    let fullStr = ''
    for (let i = 0; i <= 0x10ffff; i++) fullStr += String.fromCodePoint(i)
  JS

  map = RegexpPropertyValues.all.each.with_object({}) do |prop, hash|
    name_in_js, matched_chars = js_context.eval <<-JS rescue nil
      try {
        // 4 backslashes in Ruby String => 2 in JS String => 1 in RegExp body
        ["#{prop.name}", fullStr.match(new RegExp("\\\\p{#{prop.name}}", "gu"))]
      } catch (e1) {
        try {
          // also try with "Script=" prefix
          // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes
          ["Script=#{prop.name}", fullStr.match(new RegExp("\\\\p{Script=#{prop.name}}", "gu"))]
        } catch (e2) {}
      }
    JS

    if name_in_js.nil?
      puts "🟠 #{prop.name} (not supported by JS)"
    elsif CharacterSet.of_property(prop) != CharacterSet.new(matched_chars)
      puts "🟡 #{prop.name} (different behavior in JS)"
    else
      hash[prop] = name_in_js
      puts "🟢 #{prop.name}"
    end
  end

  File.open("#{__dir__}/../lib/js_regex/utils/property_map.csv", 'w') do |f|
    f.puts '# THIS FILE IS GENERATED BY $ rake build_prop_map - DO NOT EDIT'
    map.each { |prop, name_in_js| f.puts "#{prop.identifier},#{name_in_js}" }
  end
end
