# frozen_string_literal: true

require 'open-uri'
require 'net/http'

APK_TEST_CASES_URL = 'https://raw.githubusercontent.com/alpinelinux/apk-tools/6052bfef57a81d82451b4cad86f78a2d01959767/tests/version.data'
VERSION_SEGMENT = '([a-zA-Z0-9.\-_]+)'
WHITESPACE = '\s*'
COMPARISON_OPERATOR = '[><=]'
LEADING_ZERO_REGEX = /(^|\.)0\d/
COMPARISON_HASH = {
  '>' => 1,
  '<' => -1,
  '=' => 0
}.freeze

# Fetch test cases and convert each line into an array
apk_test_cases = Net::HTTP.get(URI(APK_TEST_CASES_URL)).each_line.to_a
parsed_test_cases = []
apk_test_cases.each_with_index do |test_case, index|
  # Exclude invalid version
  if test_case.include?('23_foo > 4_beta')
    parsed_test_cases << "# ['23_foo', 1, '4_beta'], # Excluding as 23_foo is an invalid version"
    next
  end

  # Exclude unsupported version
  if test_case.include?('0.1.0_alpha_pre2 < 0.1.0_alpha')
    parsed_test_cases << "# ['0.1.0_alpha_pre2', -1, '0.1.0_alpha'], # Multiple suffixes not supported yet"
    next
  end

  # Extract comment from test case if present
  comment = test_case.include?('#') ? test_case.split('#').last.strip : nil

  # Remove comment from the test_case
  test_case = test_case.split('#').first.strip

  # Extract versions and comparison
  if (match = test_case.match(/#{VERSION_SEGMENT}#{WHITESPACE}(#{COMPARISON_OPERATOR})#{WHITESPACE}#{VERSION_SEGMENT}/))
    version1 = match[1].strip
    comparison = match[2].strip
    version2 = match[3].strip
    comparison_value = COMPARISON_HASH[comparison]

    # Comment out test cases with leading zero as they are not supported yet
    leading_zero_case = version1.match?(LEADING_ZERO_REGEX) || version2.match?(LEADING_ZERO_REGEX)
    parsed_test_case = if leading_zero_case
                         '# '
                       else
                         ''
                       end
    # Format test case as ruby array
    parsed_test_case += "['#{version1}', #{comparison_value}, '#{version2}']"

    # Exclude comma for last item
    parsed_test_case += ',' unless index == apk_test_cases.size - 1

    # Append original comment from apk-tools if present
    parsed_test_case += " # #{comment}" if comment

    # Add comment for test cases that have leading zero
    parsed_test_case += ' # Numbers with leading zero not supported yet' if leading_zero_case

    parsed_test_cases << parsed_test_case
  else
    throw 'Invalid test case'
  end
end

# Save test cases to file
File.open('spec/apk_test_cases.rb', 'w') do |file|
  file.puts '# APK_TOOLS_TEST_CASES imported from https://github.com/alpinelinux/apk-tools/blob/6052bfef57a81d82451b4cad86f78a2d01959767/tests/version.data'
  file.puts 'APK_TOOLS_TEST_CASES = ['
  file.puts parsed_test_cases.map { |test_case| "    #{test_case}" }.join("\n")
  file.print ']'
end
