package config

import (
	"context"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/secretsmanager"
	"github.com/creasty/defaults"
	"github.com/go-playground/validator/v10"
	"github.com/imdario/mergo"
	"github.com/mitchellh/mapstructure"
	"github.com/pingcap/errors"
	"github.com/spf13/viper"
	ov "github.com/tidbcloud/config-service/oneconfig/viper"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"gopkg.in/yaml.v2"
)

var configInitOnce sync.Once

// use defaults <- pulumi config (config file) <- remote config <- secrets
// defaults for tag default in the config struct.

// use a single instance of Validate, it caches struct info
var validate = validator.New()

func NormalizeConfigDefaults(config *CentralConfig) error {
	return defaults.Set(config)
}

func NormalizeConfigSetup(config *CentralConfig) error {
	err := viper.Unmarshal(config)
	if err != nil {
		return errors.Annotate(err, "failed unmarshal from viper")
	}

	// let's load some secret from aws and merge it
	if config.ServerConfig.SecretStore != nil {
		secretConfig, err := GetSecretFromAwsSecretManager(config.ServerConfig.SecretStore.SecretKey, config.ServerConfig.SecretStore.Region)
		if err != nil {
			return errors.Annotate(err, "failed to load secret config from aws")
		}
		m := make(map[interface{}]interface{})
		if err := yaml.Unmarshal([]byte(secretConfig), &m); err != nil {
			return errors.Annotate(err, "failed to unmarshal secret config")
		}

		var s CentralConfig

		decoderConfig := &mapstructure.DecoderConfig{
			WeaklyTypedInput: true,
			Result:           &s,
			MatchName:        func(key, tagName string) bool { return strings.EqualFold(key, tagName) },
		}
		decoder, err := mapstructure.NewDecoder(decoderConfig)
		if err != nil {
			return errors.Annotate(err, "failed to create mapstructure decoder")
		}
		if err := decoder.Decode(m); err != nil {
			return errors.Annotate(err, "failed to mapsturcture secret config")
		}
		if err := mergo.Merge(config, s, mergo.WithOverride); err != nil {
			return errors.Annotate(err, "failed to merge secret config")
		}
	}
	return nil
}

func NormalizeConfigValidate(config *CentralConfig) error {
	// validate the values
	if err := validate.Struct(config); err != nil {
		return errors.Annotate(err, "failed to validate the config values")
	}

	return nil
}

func NormalizeConfig() error {
	config := &CentralConfig{}

	err := NormalizeConfigDefaults(config)
	if err != nil {
		return errors.Annotate(err, "config defaults")
	}
	err = NormalizeConfigSetup(config)
	if err != nil {
		return errors.Annotate(err, "config setup")
	}
	err = NormalizeConfigValidate(config)
	if err != nil {
		return errors.Annotate(err, "config validate")
	}
	globalConf = config
	return nil
}

// InitConfig parse the central configuration file and init the global config var
func InitConfig(path string) error {
	var err error
	ctx := context.Background()
	//tilog.Info(ctx, "init config, print stacktrace", zap.Stack("stacktrace"))

	configInitOnce.Do(func() {
		viper.SetConfigFile(path)
		tilog.Info(ctx, "using config file", zap.String("file", viper.ConfigFileUsed()))
		err = viper.ReadInConfig()
		if err != nil {
			return
		}
		if viper.GetString("server.sentry.env") == "local" {
			tilog.Info(ctx, "Load OneConfig from local")
			err = LoadOneConfigInLocal(ctx)
		} else {
			tilog.Info(ctx, "Load OneConfig from remote")
			err = LoadRemote()
		}
		if err != nil {
			tilog.Warn(ctx, "load remote config failed, just ignore it in persnonal project", zap.Error(err))
		}

		err = NormalizeConfig()
	})

	return err
}

func LoadOneConfigInLocal(ctx context.Context) error {
	localOneConfigPath := "/etc/dbaas/onecnofig-local.yaml"
	if _, err := os.Stat(localOneConfigPath); err != nil {
		tilog.Info(ctx, "local one config path is not found, skip")
		return nil
	}

	viper.SetConfigFile(localOneConfigPath)
	err := viper.MergeInConfig()
	return err
}
func LoadRemote() error {
	ctx := context.Background()
	remote := "oneconfig-account/config.yaml"
	tilog.Info(ctx, "Read From Remote", zap.String("remote", remote))
	err := viper.AddRemoteProvider(ov.Provider, ov.Endpoint, remote)
	if err != nil {
		return errors.Annotate(err, "failed to load remote config")
	}

	err = viper.ReadRemoteConfig()
	if err != nil {
		return errors.Annotate(err, "failed to load remote config")
	}

	tilog.Info(ctx, "get value from viper path:  "+remote)
	//tilog.Info(ctx, "get value from viper ", zap.Any("rbac.systems", viper.GetStringSlice("rbac.systems")))

	// open a goroutine to watch remote changes forever
	go func() {
		var errNum = 0
		for {
			time.Sleep(time.Minute * 1) // delay after each request

			// currently, only tested with etcd support
			err := viper.WatchRemoteConfig()
			if err != nil {
				tilog.Warn(ctx, "unable to read remote config", zap.Error(err))
				errNum += 1
				if errNum%GetErrReportFreqNum() == 0 {
					tilog.Error(ctx, "unable to read remote config", zap.Error(err))
				}
				continue
			}

			err = NormalizeConfig()
			if err != nil {
				tilog.Warn(ctx, "failed to normalize config", zap.Error(err))
				errNum += 1
				if errNum%GetErrReportFreqNum() == 0 {
					tilog.Error(ctx, "unable to read remote config", zap.Error(err))
				}
				continue
			}
		}
	}()
	return nil
}

func Global() *CentralConfig {
	return globalConf
}

func GetSecretFromAwsSecretManager(secretName, region string) (string, error) {
	awsConfig := aws.NewConfig().WithMaxRetries(3).WithRegion(region)
	opts := session.Options{Config: *awsConfig}
	sess, err := session.NewSessionWithOptions(opts)
	if err != nil {
		return "", err
	}
	svc := secretsmanager.New(sess)
	input := &secretsmanager.GetSecretValueInput{
		SecretId:     aws.String(secretName),
		VersionStage: aws.String("AWSCURRENT"), // VersionStage defaults to AWSCURRENT if unspecified
	}
	result, err := svc.GetSecretValue(input)
	if err != nil {
		return "", err
	}
	return *result.SecretString, nil
}

var (
	configPath = "/etc/dbaas/config.yaml"
)

func SetConfigPath(cfgPath string) {
	configPath = cfgPath
}

func NewConfig() (*CentralConfig, error) {
	err := InitConfig(configPath)

	return Global(), err
}
