# typed: false
# frozen_string_literal: true
T.bind(self, T.all(Rake::DSL, Object))

namespace :metrics do
  desc "run reporters periodically"
  task report_all: %i[environment set_logger_stdout] do
    schedule = {
      Rake::Task["metrics:jobs"] => 60.seconds,
      Rake::Task["metrics:estimate_db_rows"] => 60.seconds,
    }

    last_ran = {}
    while true
      schedule.each do |task, run_every|
        task_name = task.name
        if last_ran[task_name].nil? || last_ran[task_name] < run_every.ago
          begin
            task.execute
          rescue NotImplementedError, StandardError => e
            Rails.logger.error("error invoking #{task_name}: #{e.message.red}")
          end
          last_ran[task_name] = Time.now
        end
      end
      sleep_amt = schedule.values.min
      puts "sleeping #{sleep_amt}"
      sleep sleep_amt
    end
  end
end
