# frozen_string_literal: true

module ReleaseTools
  module Deployments
    class BlockersMetrics
      include ::SemanticLogger::Loggable

      def initialize
        @client = Metrics::Client.new
        @fetcher = ReleaseTools::Deployments::BlockerIssueFetcher.new
      end

      def execute
        return unless Feature.enabled?(:deployment_blockers_metrics)

        @fetcher.fetch
        blockers = @fetcher.deployment_blockers

        calculator = ReleaseTools::Deployments::BlockersCalculator.new(blockers)
        blocker_types = calculator.blocker_types

        root_cause_list.each do |root_cause|
          blocked_time = blocker_types[root_cause] || { gprd: 0, gstg: 0, count: 0 }
          log_blocker_metric(root_cause, blocked_time)
          create_metric_for(root_cause, blocked_time)
        end
      end

      private

      attr_reader :client

      def week
        @fetcher.start_time.strftime('%Y-%m-%d')
      end

      def root_cause_list
        [
          "RootCause::Broken-Security-Mirror",
          "RootCause::Config-Change",
          "RootCause::DB-Migration",
          "RootCause::Dev-Instance",
          "RootCause::External-Dependency",
          "RootCause::Feature-Flag",
          "RootCause::Flaky-Test",
          "RootCause::Indeterminate",
          "RootCause::Known-Software-Issue",
          "RootCause::Native-Traffic",
          "RootCause::Needed",
          "RootCause::Ops-Instance",
          "RootCause::Release-Compatibility",
          "RootCause::Saturation",
          "RootCause::Software-Change",
          "RootCause::SPoF",
          "Change-request"
        ]
      end

      def create_metric_for(root_cause, blocked_time)
        hours_gprd_blocked = blocked_time[:gprd]
        hours_gstg_blocked = blocked_time[:gstg]
        blockers_per_category = blocked_time[:count]

        client.set(
          'deployment_blocker_count',
          blockers_per_category,
          labels: "#{root_cause},#{week}"
        )

        client.set(
          'deployment_hours_blocked',
          hours_gprd_blocked,
          labels: "#{root_cause},gprd,#{week}"
        )

        client.set(
          'deployment_hours_blocked',
          hours_gstg_blocked,
          labels: "#{root_cause},gstg,#{week}"
        )
      end

      def log_blocker_metric(root_cause, blocked_time)
        logger.info(
          "Setting deployment blockers metric for #{root_cause}",
          blockers_per_category: blocked_time[:count],
          hours_gprd_blocked: blocked_time[:gprd],
          hours_gstg_blocked: blocked_time[:gstg],
          labels: {
            root_cause: root_cause,
            week: week
          }
        )
      end
    end
  end
end
