package config

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/viper"
	"strings"
)

const (
	envConfigPrefix = "XH_G"
)

// LoadConfig 加载并返回应用配置
func LoadConfig[T any](configDir string, configPtr *T) (*T, error) {
	v := viper.New()

	v.SetEnvPrefix(envConfigPrefix)
	v.AutomaticEnv()
	v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

	env := v.GetString("env")
	if env == "" {
		env = "dev"
	}

	v.SetConfigName(fmt.Sprintf("config.%s", strings.ToLower(env)))
	v.AddConfigPath(configDir)
	v.SetConfigType("yaml")

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

	if err := v.Unmarshal(&configPtr); err != nil {
		return nil, fmt.Errorf("failed to unmarshal config: %w", err)
	}

	marshal, _ := json.Marshal(configPtr)
	fmt.Printf("Configuration loading completed: %v\n", string(marshal))
	return configPtr, nil
}
