# frozen_string_literal: true

require 'clamp'
require 'json'

module Abaci
  # CLI entry point
  class CLI < Clamp::Command
    include Base

    option(['-l', '--last'], 'N', 'How long to go back in time.', default: '30m') { |value| Abaci.config[:last] = value }
    option(['-d', '--dry-run'], :flag, 'Dry runs do not write data.', default: false) { Abaci.config[:dry_run] = true }
    option(['-D', '--debug'], :flag, 'Outputs additional debug data to the console.', default: false) { Abaci.config[:debug] = true }
    option(['-p', '--profile'], 'PROFILE', 'What AWS profile to use for authentication.', default: nil) { |value| Abaci.config[:aws_profile] = value }

    def execute
      start_time = Time.now

      success = Influx.write_error_rates
      success = Influx.write_error_rates_by_build && success

      lapsed = Time.now - start_time
      puts "Wrote error rates to Influx.  Took #{lapsed} seconds." if success
      puts "Did not write error rates to Influx.  Took #{lapsed} seconds." unless success

      return if config(:dry_run)

      status = success ? :ok : :critical
      Abaci.notify_sensu status

    rescue StandardError => e
      puts "Error: Captured exception! #{e.message}"
      Abaci.notify_sensu :critical, e.message
      raise
    end
  end
end
