package utils

import (
	"fmt"
	"strconv"
	"strings"
)

const (
	regionsPrefix  = "regions/"
	awsPrefix      = "aws-"
	gcpPrefix      = "gcp-"
	azurePrefix    = "azure-"
	alicloudPrefix = "alicloud-"

	AwsProvider      = "aws"
	GcpProvider      = "gcp"
	AzureProvider    = "azure"
	AlicloudProvider = "alicloud"

	// Labels
	OrgIDLabelKey     = "tidb.cloud/organization"
	ProjectIDLabelKey = "tidb.cloud/project"
)

func ConvertRegionName(region string) string {
	// e.g. regions/aws-us-east-1
	region = strings.TrimPrefix(region, regionsPrefix)
	region = strings.TrimPrefix(region, awsPrefix)
	region = strings.TrimPrefix(region, gcpPrefix)
	region = strings.TrimPrefix(region, azurePrefix)
	region = strings.TrimPrefix(region, alicloudPrefix)

	return region
}

func ConvertRegionToMgmt(region, provider string) string {
	return fmt.Sprintf("%s%s-%s", regionsPrefix, strings.ToLower(provider), strings.ToLower(region))
}

// nodeSpecKey: "xCxG" -> "x" is the number of CPU cores, "G" is the memory size in GB
// e.g. "4C8G" -> 4 ， "32C128G-IO2" -> 32
func GetCpuNum(nodeSpecKey string) int {
	before, _, ok := strings.Cut(nodeSpecKey, "C")
	if !ok {
		return 0
	}
	cpu, err := strconv.Atoi(before)
	if err != nil {
		return 0
	}
	return cpu
}

// nodeSpecKey: "xCxG" -> "x" is the number of CPU cores, "G" is the memory size in GB
// e.g. "4C8G" -> 8 ， "32C128G-IO2" -> 128
func GetMemorySize(nodeSpecKey string) int {
	index := strings.Index(nodeSpecKey, "C")
	if index == -1 {
		return 0
	}
	nodeSpecKey = nodeSpecKey[index+1:]
	index = strings.Index(nodeSpecKey, "G")
	if index == -1 {
		return 0
	}

	mem, err := strconv.Atoi(nodeSpecKey[:index])
	if err != nil {
		return 0
	}

	return mem
}
