package config

import (
	"fmt"
	"os"

	"github.com/pingcap/log"
	"github.com/spf13/viper"
	"go.uber.org/zap/zapcore"
)

const (
	envInitErrorMsg = "ENV[%s] is not set, failed to init"
)

var (
	AwsRegion string
	HostName  string

	ProviderProjectID string
)

func GetEnvConfig() error {
	AwsRegion := os.Getenv("AWS_REGION")
	if AwsRegion == "" {
		return fmt.Errorf(envInitErrorMsg, "AWS_REGION")
	}
	return nil
}

func InitViper(filePath string) error {
	viper.SetConfigFile(filePath)
	viper.SetConfigType("ini")

	err := viper.ReadInConfig()
	if err != nil {
		return fmt.Errorf("read config failed: %v", err)

	}
	return err
}

func SetLogLevel(key string) error {
	kv := map[string]zapcore.Level{}

	for i := zapcore.DebugLevel; i <= zapcore.FatalLevel; i++ {
		kv[i.String()] = i
	}

	level, ok := kv[key]
	if !ok {
		return fmt.Errorf("param error")
	}
	log.SetLevel(level)
	return nil
}
