package eventstream

import (
	"context"
	"log"
	"strings"

	"code.justin.tv/eventbus/admin-cli/internal/client"
	"code.justin.tv/eventbus/admin-cli/internal/environment"

	"code.justin.tv/eventbus/admin-cli/internal/output"
	"code.justin.tv/eventbus/controlplane/rpc"

	"github.com/spf13/cobra"
)

const (
	highFrequencyThreshold = 400
	lowFrequencyThreshold  = 30

	highFrequencyKey    = "High"
	lowFrequencyKey     = "Low"
	veryLowFrequencyKey = "Very Low"
)

var (
	freqGet string
	freqEnv string
)

func init() {
	getAlarmFrequencyEventStreamsCommand.Flags().StringVarP(&freqGet, "event-type", "t", "", "underlying event type for which to get stats for")
	getAlarmFrequencyEventStreamsCommand.MarkFlagRequired("event-type")
	getAlarmFrequencyEventStreamsCommand.Flags().StringVarP(&freqEnv, "environment", "e", "", "environment to query")
	getAlarmFrequencyEventStreamsCommand.MarkFlagRequired("environment")
}

var getAlarmFrequencyEventStreamsCommand = &cobra.Command{
	Use:   "frequency",
	Short: "Get the alarm frequency of an event stream",
	Run: func(cmd *cobra.Command, args []string) {
		ctx := context.Background()
		config, err := environment.Resolve()
		if err != nil {
			log.Fatal("Error resolving runtime environment: ", err.Error())
		}

		c, err := client.NewEventStreams(config)
		if err != nil {
			log.Fatal("Error creating event streams client: ", err.Error())
		}

		resp, err := c.GetStats(ctx, &rpc.GetEventStreamStatsReq{
			EventType:   freqGet,
			Environment: freqEnv,
		})
		if err != nil {
			log.Fatal("Error fetching event stream stats: ", err.Error())
		}

		minEventsPerMin := resp.GetMinEventsPerMinute()
		if minEventsPerMin == nil {
			log.Fatal("Minimum events per min was null")
		}

		var frequency string
		if minEventsPerMin.GetValue() >= highFrequencyThreshold {
			frequency = highFrequencyKey
		} else if minEventsPerMin.GetValue() >= lowFrequencyThreshold {
			frequency = lowFrequencyKey
		} else {
			frequency = veryLowFrequencyKey
		}

		minEvents := "0"
		eventData := strings.Split(minEventsPerMin.String(), ":")

		// should be of the form "value:X" or "" if no event data exists
		if len(eventData) == 2 {
			minEvents = eventData[1]
		}

		output.MapMsg("Event Stream Frequency", map[string]string{
			"Event Type":                freqGet,
			"Environment":               freqEnv,
			"Minimum Events per Minute": minEvents,
			"Frequency":                 frequency,
		})
	},
}
