package config

import "os"

// Config STT 语音识别服务配置
type Config struct {
	Port            string
	WhisperBinary   string
	WhisperModel    string
	WhisperLanguage string
	MaxAudioSize    int64 // 字节

	// DashScope STT 配置
	DashScopeAPIKey          string
	DashScopeModel           string // 离线/非实时 ASR 模型
	DashScopeSTTRealtime     string // 实时 ASR 模型
}

// Load 从 models.json 和环境变量加载配置。
// models.json 优先级高于环境变量。
func Load() *Config {
	// 从 models.json 加载 ASR 配置
	modelsAPIKey, modelsOffline, modelsRealtime := LoadModelsConfig()

	// .env / 环境变量作为回退
	envAPIKey := getEnv("DASHSCOPE_API_KEY", "")
	envModel := getEnv("DASHSCOPE_STT_MODEL", "qwen3-asr-flash-2026-02-10")
	envRealtime := getEnv("DASHSCOPE_STT_REALTIME_MODEL", "qwen3-asr-flash-realtime")

	apiKey := modelsAPIKey
	if apiKey == "" {
		apiKey = envAPIKey
	}
	offlineModel := modelsOffline
	if offlineModel == "" {
		offlineModel = envModel
	}
	realtimeModel := modelsRealtime
	if realtimeModel == "" {
		realtimeModel = envRealtime
	}

	return &Config{
		Port:                 getEnv("PORT", "8093"),
		WhisperBinary:        getEnv("WHISPER_BINARY", "./whisper.cpp/main"),
		WhisperModel:         getEnv("WHISPER_MODEL", "./whisper.cpp/models/ggml-small.bin"),
		WhisperLanguage:      getEnv("WHISPER_LANGUAGE", "zh"),
		MaxAudioSize:         10 * 1024 * 1024, // 10MB
		DashScopeAPIKey:      apiKey,
		DashScopeModel:       offlineModel,
		DashScopeSTTRealtime: realtimeModel,
	}
}

func getEnv(key, fallback string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return fallback
}
