package config

import (
	"fmt"
	"os"

	"github.com/tidbcloud/infra-provider/pkg/config"
	"sigs.k8s.io/yaml"
)

var (
	conf *Config
	//once sync.Once
)

const (
	EnvKeyClinicActivityToken = "CLINIC_ACTIVITY_TOKEN"
)

type ServerConfig struct {
	// DeploymentRegion represents which region is config-manager deployed in
	// When the config-manager is deployed in global, this field is empty.
	DeploymentRegion string `json:"deploymentRegion"`

	Activity ActivityConfig `json:"activity"`
}

func (c ServerConfig) IsGloballyDeployed() bool {
	return c.DeploymentRegion == ""
}

// ActivityConfig is the config using to send activity/event to clinic
type ActivityConfig struct {
	Enabled              bool   `yaml:"enabled" json:"enabled"`
	ClinicEndpoint       string `yaml:"clinicEndpoint" json:"clinicEndpoint"`
	ClinicToken          string `yaml:"clinicToken" json:"clinicToken"`
	ActivityHubEndpoint  string `yaml:"activityHubEndpoint" json:"activityHubEndpoint"`
	ActivityHubSource    string `yaml:"activityHubSource" json:"activityHubSource"`
	ActivityHubSourceKey string `yaml:"activityHubSourceKey" json:"activityHubSourceKey"`
}

type Config struct {
	Server       ServerConfig                                  `json:"server"`
	FeatureGates map[config.FeatureGateName]config.FeatureGate `json:"featureGates"`
}

func Global() *Config {
	return conf
}

func InitConfig(path string) {
	data, err := os.ReadFile(path)
	if err != nil {
		panic(fmt.Errorf("read config file: %w", err))
	}
	conf = &Config{}
	err = yaml.Unmarshal(data, conf)
	if err != nil {
		panic(fmt.Errorf("unmarshal config: %w", err))
	}
}
