package config

import (
	"fmt"
	"os"
	"sync"

	"gopkg.in/yaml.v3"
)

var (
	ConfigManager = &Config{}
	configLock    = &sync.RWMutex{}
	configLoaded  = false
)

type Config struct {
	SteamApiKey      string `yaml:"steam_api_key"`
	OpenaiApiKey     string `yaml:"openai_api_key"`
	OpenaiApiBaseUrl string `yaml:"openai_api_base_url"`
	OpenaiModelName  string `yaml:"openai_model_name"`
	OpenaiPrompt     string `yaml:"openai_prompt"`
	Management       struct {
		Admin         int64  `yaml:"admin"`
		ReportGroup   int64  `yaml:"report_group"`
		ProxyAddr     string `yaml:"proxy_addr"`
		NapcatWsSrv   string `yaml:"napcat_ws_srv"`
		NapcatHttpSrv string `yaml:"napcat_http_srv"`
	} `yaml:"management"`
	WebServer struct {
		Token string `yaml:"token"`
	} `yaml:"web_server"`
}

// LoadConfig 从指定路径加载配置文件
func (cm *Config) LoadConfig(path string) error {
	configLock.Lock()
	defer configLock.Unlock()

	data, err := os.ReadFile(path)
	if err != nil {
		return fmt.Errorf("读取配置文件失败: %w", err)
	}

	err = yaml.Unmarshal(data, cm)
	if err != nil {
		return fmt.Errorf("解析配置文件失败: %w", err)
	}

	configLoaded = true
	return nil
}

// GetConfig 获取配置实例，如果未加载则尝试从默认路径加载
func (cm *Config) GetConfig() *Config {
	configLock.RLock()
	if configLoaded {
		configLock.RUnlock()
		return cm
	}
	configLock.RUnlock()

	// 如果当前实例是ConfigManager但配置尚未加载，尝试加载
	if cm == ConfigManager {
		err := ConfigManager.LoadConfig("config.yml")
		if err != nil {
			panic(fmt.Errorf("加载默认配置失败: %w", err))
		}
	}

	return cm
}

// ReloadConfig 重新加载配置
func ReloadConfig(path string) error {
	return ConfigManager.LoadConfig(path)
}
