#!/usr/bin/env ruby
# frozen_string_literal: true

require "bundler/setup"
require "optparse"

require_relative "../lib/gitlab_quality/test_tooling"

params = {}
HEALTH_PROBLEM_TYPES = GitlabQuality::TestTooling::Report::TestHealthIssueFinder::HEALTH_PROBLEM_TYPE_TO_LABEL.keys

options = OptionParser.new do |opts|
  opts.banner = "Usage: #{$PROGRAM_NAME} [options]"

  opts.on('-i', '--input-files INPUT_FILES', String, 'JSON rspec-retry report files') do |input_files|
    params[:input_files] = input_files
  end

  opts.on('-p', '--project PROJECT', String, 'Can be an integer or a group/project string') do |project|
    params[:project] = project
  end

  opts.on('-t', '--token TOKEN', String, 'A valid access token with `api` scope and Maintainer permission in PROJECT') do |token|
    params[:token] = token
  end

  opts.on("--health-problem-type PROBLEM_TYPE", String, "Look for the given health problem type (#{HEALTH_PROBLEM_TYPES.join(', ')})") do |value|
    raise ArgumentError, "Invalid health problem type: #{value}. Valid options are: #{HEALTH_PROBLEM_TYPES.join(', ')}" unless HEALTH_PROBLEM_TYPES.include?(value)

    params[:health_problem_type] = value
  end

  opts.on_tail('-v', '--version', 'Show the version') do
    require_relative "../lib/gitlab_quality/test_tooling/version"
    puts "#{$PROGRAM_NAME} : #{GitlabQuality::TestTooling::VERSION}"
    exit
  end

  opts.on_tail('-h', '--help', 'Show the usage') do
    puts "Purpose: Checks whether tests coming from the rspec JSON report files has an existing test health issue opened."
    puts opts
    exit
  end

  opts.parse(ARGV)
end

if params.any?
  raise ArgumentError, "No health problem type given. Valid options are: #{HEALTH_PROBLEM_TYPES.join(', ')}" unless params.key?(:health_problem_type)

  if GitlabQuality::TestTooling::Report::TestHealthIssueFinder.new(**params).found_existing_unhealthy_test_issue?
    exit 0
  else
    exit 1
  end
else
  puts options
  exit 1
end
