package scrape

import (
	"encoding/json"
	"fmt"
	"strings"

	tidbClusterV1alpha1 "github.com/pingcap/tidb-operator/pkg/apis/pingcap/v1alpha1"
	"github.com/pingcap/tidb-operator/pkg/pdapi"

	"github.com/tidbcloud/billing-reporter/conf"
	"github.com/tidbcloud/billing-reporter/report"
)

const (
	TypeAttributeName = "type"
	EventMessage      = "event"
	HeartbeatMessage  = "heartbeat"

	FromAttributeName   = "from"
	ObjectAttributeName = "object"

	TiDBClusterObject = "tidbcluster"
	PodObject         = "pod"

	MessageVersionAttributeName = "messageVersion"
	MessageVersion1             = "1"
	MessageVersion2             = "2"
)

func getPodNameFromStore(info *pdapi.StoreInfo) string {
	ip := strings.Split(info.Store.GetAddress(), ":")[0]
	podName := strings.Split(ip, ".")[0]
	return podName
}

func getLabelsFromStore(store *pdapi.StoreInfo) map[string]string {
	l := map[string]string{}
	for _, label := range store.Store.Labels {
		l[label.Key] = label.Value
	}
	return l
}

func BuildSqsMessage(info []*TidbClusterHeartbeatInfo) (report.SqsMessage, error) {
	b, err := json.Marshal(info)
	if err != nil {
		return report.SqsMessage{}, err
	}
	return report.SqsMessage{
		Message: string(b),
		// already checked length
		Partition: fmt.Sprintf("%d", info[0].TenantId),
		Attributes: map[string]string{
			TypeAttributeName:           HeartbeatMessage,
			ObjectAttributeName:         TiDBClusterObject,
			FromAttributeName:           conf.HostName,
			MessageVersionAttributeName: MessageVersion2,
		},
	}, nil
}

// getComponentReplicas returns the number of replicas of components from TidbCluster's Spec, which will avoid nil pointer.
func getComponentReplicas(tc *tidbClusterV1alpha1.TidbCluster) (tidbReplica, tikvReplica, tiflashReplica int32) {
	if tc != nil {
		if tc.Spec.TiDB != nil {
			tidbReplica = tc.Spec.TiDB.Replicas
		}
		if tc.Spec.TiKV != nil {
			tikvReplica = tc.Spec.TiKV.Replicas
		}
		if tc.Spec.TiFlash != nil {
			tiflashReplica = tc.Spec.TiFlash.Replicas
		}
	}
	return
}
