package config

import (
	"context"
	"time"

	"github.com/spf13/viper"
	ov "github.com/tidbcloud/config-service/oneconfig/viper"
	"github.com/tidbcloud/tiinf/errs"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
)

func LoadRemoteConfig(ctx context.Context) error {
	remote := "oneconfig-account/config.yaml"

	err := viper.AddRemoteProvider(ov.Provider, ov.Endpoint, remote)
	if err != nil {
		tilog.Error(ctx, "viper add remote provider error", zap.String("remote", remote), zap.Any("err", err))
		return errs.NewInternalUnknown("failed to load remote config", err)
	}
	viper.SetConfigType("yaml")
	err = viper.ReadRemoteConfig()
	if err != nil {
		tilog.Error(ctx, "viper read remote config error", zap.String("remote", remote), zap.Any("err", err))
		return errs.NewInternalUnknown("failed to load remote config", err)
	}
	go watchViperConfig(ctx)

	tilog.Info(ctx, "viper load remote config success", zap.String("remote", remote))
	testViper()
	return nil
}

func testViper() {
	ctx := context.Background()
	all := viper.AllSettings()
	tilog.Info(ctx, "test viper all settings", zap.Any("all", all))
}

func watchViperConfig(ctx context.Context) {
	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 {
			errNum += 1
			if errNum%5 == 0 {
				tilog.Error(ctx, "unable to read remote config", zap.Error(err))
			} else {
				tilog.Info(ctx, "unable to read remote config", zap.Error(err))

			}
		}
		testViper()
	}
}
