package main

import (
	"fmt"
	"github.com/spf13/viper"
	"os"
)

type Config struct {
	App struct {
		Name  string `mapstructure:"name"`
		Port  int    `mapstructure:"port"`
		Debug bool   `mapstructure:"debug"`
	} `mapstructure:"app"`
	Database struct {
		Host     string `mapstructure:"host"`
		Port     int    `mapstructure:"port"`
		Username string `mapstructure:"username"`
		Password string `mapstructure:"password"`
		DBName   string `mapstructure:"dbname"`
	} `mapstructure:"database"`
}

func LoadConfig(env string) (*Config, error) {
	// 根据环境加载配置文件
	configName := fmt.Sprintf("config.%s", env)

	viper.SetConfigName(configName)
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")

	if err := viper.ReadInConfig(); err != nil {
		return nil, err
	}

	var config Config
	if err := viper.Unmarshal(&config); err != nil {
		return nil, err
	}

	return &config, nil
}

func main() {
	// 从环境变量读取环境名称
	env := os.Getenv("APP_ENV")
	if env == "" {
		env = "dev" // 默认开发环境
	}

	fmt.Printf("Loading config for environment: %s\n", env)

	config, err := LoadConfig(env)
	if err != nil {
		panic(err)
	}

	fmt.Printf("App: %s\n", config.App.Name)
	fmt.Printf("Port: %d\n", config.App.Port)
	fmt.Printf("Debug: %v\n", config.App.Debug)
	fmt.Printf("Database: %s@%s:%d/%s\n",
		config.Database.Username,
		config.Database.Host,
		config.Database.Port,
		config.Database.DBName,
	)
}
