# frozen_string_literal: true

require "json"
require "open-uri"
require "time"

def generate_spdx_license_list(dest = "lib/rubygems/util/licenses.rb")
  base = URI("https://spdx.org/licenses/")
  updates = [
    %w[licenses licenseId isDeprecatedLicenseId],
    %w[exceptions licenseExceptionId isDeprecatedLicenseId],
  ].map do |uri, id, deprecated_id|
    (base + "#{uri}.json").open do |f|
      begin
        mtime = Time.parse(f.meta["last-modified"])
      rescue ArgumentError
      end
      valid = []
      deprecated = []
      JSON.parse(f.read)[uri].each do |o|
        if o[deprecated_id]
          deprecated << o[id]
        else
          valid << o[id]
        end
      end
      [mtime, valid, deprecated]
    end
  end

  mtime = updates.filter_map {|t,| t }.max
  (_, valid_licenses, deprecated_licenses), (_, valid_exceptions, deprecated_exceptions) = updates

  content = "#{<<-RUBY}#{<<-'RUBY'}"
# frozen_string_literal: true

# This is generated by #{File.basename(__FILE__)}, any edits to this
# file will be discarded.

require_relative "../text"

class Gem::Licenses
  extend Gem::Text

  NONSTANDARD = "Nonstandard"
  LICENSE_REF = "LicenseRef-.+"

  # Software Package Data Exchange (SPDX) standard open-source software
  # license identifiers
  LICENSE_IDENTIFIERS = %w[
    #{valid_licenses.sort.join "\n    "}
  ].freeze

  DEPRECATED_LICENSE_IDENTIFIERS = %w[
    #{deprecated_licenses.sort.join "\n    "}
  ].freeze

  # exception identifiers
  EXCEPTION_IDENTIFIERS = %w[
    #{valid_exceptions.sort.join "\n    "}
  ].freeze

  DEPRECATED_EXCEPTION_IDENTIFIERS = %w[
    #{deprecated_exceptions.sort.join "\n    "}
  ].freeze

  RUBY
  VALID_REGEXP = /
    \A
    (?:
      #{Regexp.union(LICENSE_IDENTIFIERS)}
      \+?
      (?:\s WITH \s #{Regexp.union(EXCEPTION_IDENTIFIERS)})?
      | #{NONSTANDARD}
      | #{LICENSE_REF}
    )
    \Z
  /ox

  DEPRECATED_LICENSE_REGEXP = /
    \A
    #{Regexp.union(DEPRECATED_LICENSE_IDENTIFIERS)}
    \+?
    (?:\s WITH \s .+?)?
    \Z
  /ox

  DEPRECATED_EXCEPTION_REGEXP = /
    \A
    .+?
    \+?
    (?:\s WITH \s #{Regexp.union(DEPRECATED_EXCEPTION_IDENTIFIERS)})
    \Z
  /ox

  def self.match?(license)
    VALID_REGEXP.match?(license)
  end

  def self.deprecated_license_id?(license)
    DEPRECATED_LICENSE_REGEXP.match?(license)
  end

  def self.deprecated_exception_id?(license)
    DEPRECATED_EXCEPTION_REGEXP.match?(license)
  end

  def self.suggestions(license)
    by_distance = LICENSE_IDENTIFIERS.group_by do |identifier|
      levenshtein_distance(identifier, license)
    end
    lowest = by_distance.keys.min
    return unless lowest < license.size
    by_distance[lowest]
  end
end
RUBY

  begin
    return if content == File.read(dest)
  rescue SystemCallError
  end
  File.binwrite(dest, content)
  [dest, mtime]
end

if $0 == __FILE__
  p generate_spdx_license_list
end
