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

require "bundler/setup"
require "optparse"

require_relative "../lib/gitlab_quality/test_tooling"

params = {}

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

  opts.on('-u', '--unstable-specs-file INPUT_FILES', String, 'File with list of unstable specs (JSON) to quarantine') do |unstable_specs_file|
    params[:unstable_specs_file] = unstable_specs_file
  end

  opts.on('-s', '--stable-specs-file INPUT_FILES', String, 'File with list of stable specs (JSON) to add :blocking meta') do |stable_specs_file|
    params[:stable_specs_file] = stable_specs_file
  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('--dry-run', "Perform a dry-run (don't create branches, commits or MRs)") do
    params[:dry_run] = true
  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: Add quarantine or blocking meta to specs"
    puts opts
    exit
  end

  opts.parse(ARGV)
end

if params.any?
  if params[:unstable_specs_file] && params[:stable_specs_file]
    puts "Please provide only one of one of -u and -s"
    exit 1
  elsif !params[:unstable_specs_file] && !params[:stable_specs_file]
    puts "Please provide at least one of one of -u and -s"
    exit 1
  end

  if params[:unstable_specs_file]
    params[:specs_file] = params.delete(:unstable_specs_file)
    params[:processor] = GitlabQuality::TestTooling::TestMeta::Processor::AddToQuarantineProcessor
  else
    params[:specs_file] = params.delete(:stable_specs_file)
    params[:processor] = GitlabQuality::TestTooling::TestMeta::Processor::AddToBlockingProcessor
  end

  GitlabQuality::TestTooling::TestMeta::TestMetaUpdater.new(**params).invoke!
else
  puts options
  exit 1
end
