# frozen_string_literal: true

require 'tegimen/logging'

require 'thor'

class TegimenCLI < Thor
  extend Tegimen::Logging

  def self.exit_on_failure?
    true
  end

  class_option :debug, desc: 'Enables debug logging.', default: false, type: :boolean
  class_option :key, desc: 'Our WPT API key, checks ENV["WPT_API_KEY"] if omitted.', required: false, type: :string
  class_option :parallelize, desc: 'Enables parallel execution where appropriate, and mutes most logging.', default: false, type: :boolean

  desc 'start TEST-SUITE', 'Starts a new set of tests based on a config file in the suites folder.'

  def start(test_suite)
    Tegimen.enable_parallel_execution if options[:parallelize]
    Tegimen::Logging.logging_level = :DEBUG if options[:debug]
    Tegimen::TestSuite.new(test_suite, api_key).start_tests
  end

  desc 'check TEST-SUITE', 'Checks the status of and moves along related in-flight tests.'
  method_option :batch_size, desc: 'The max number of tests that will be checked.', default: 100, type: :numeric

  def check(test_suite)
    Tegimen.enable_parallel_execution if options[:parallelize]
    Tegimen::Logging.logging_level = :DEBUG if options[:debug]
    Tegimen::TestSuite.new(test_suite, api_key).check_tests(batch_size: options[:batch_size])
  end

  desc 'count', 'Displays the counts of all in-flight tests'

  def count
    important 'Counting in-flight tests...'
    test_counts = Hash.new(0)

    Tegimen.s3_client.objects(prefix: 'tegimen-state').each do |obj|
      next unless File.basename(obj.key) == 'state.json'
      suite = obj.key.split('/')[1]
      test_counts[suite] += 1
    end

    important "There are a total of #{test_counts.values.reduce(0, :+)} test(s) currently in-flight.  Breakdown:"
    indent_logs

    max_suite = test_counts.keys.collect(&:length).max

    important "#{format('%*s', max_suite, 'Suite')}\tCount"
    test_counts.each do |suite, count|
      important "#{format('%*s', max_suite, suite)}\t#{count}"
    end
  end

  no_commands do
    def api_key
      if @api_key.nil? && options[:key].nil? && ENV['WPT_API_KEY'].nil?
        fatal 'You must provide an api key, either via --key or ENV["WPT_API_KEY"].'
        exit 1
      end

      @api_key = options[:key] || ENV['WPT_API_KEY']
    end
  end
end
