package config

import (
	"log"
	"os"
	"strconv"
)

// Config 持有 api-gateway 运行时配置
type Config struct {
	Port              string
	JWTSecret         string
	JWTIssuer         string
	JWTAudience       string
	ClassesServiceURL string
	IamServiceURL     string
	TeacherBffURL     string
	CoreEduServiceURL string
	ContentServiceURL string
	DataAnaServiceURL string
	MsgServiceURL     string
	AiServiceURL      string
	OTLPEndpoint      string
	LogLevel          string
	DevMode           bool
}

// devJWTSecret 是 DevMode 下的默认 JWT 密钥（仅用于本地联调，生产必须配置 JWT_SECRET）
const devJWTSecret = "p1-dev-secret-change-in-production"

// Load 从环境变量加载配置。
// 非 DevMode 下若 JWT_SECRET 未配置则 fatal 退出；DevMode 下使用默认密钥并打印 warning。
func Load() *Config {
	devMode := getEnvBool("DEV_MODE", false)
	jwtSecret := getEnv("JWT_SECRET", "")
	if jwtSecret == "" {
		if devMode {
			log.Println("warning: JWT_SECRET not set, using dev default (DEV_MODE=true)")
			jwtSecret = devJWTSecret
		} else {
			log.Fatal("JWT_SECRET must be set in non-dev mode")
		}
	}

	return &Config{
		Port:              getEnv("API_GATEWAY_PORT", "8080"),
		JWTSecret:         jwtSecret,
		JWTIssuer:         getEnv("JWT_ISSUER", "next-edu-cloud"),
		JWTAudience:       getEnv("JWT_AUDIENCE", "next-edu-cloud"),
		ClassesServiceURL: getEnv("CLASSES_SERVICE_URL", "http://localhost:3001"),
		IamServiceURL:     getEnv("IAM_SERVICE_URL", "http://localhost:3002"),
		TeacherBffURL:     getEnv("TEACHER_BFF_URL", "http://localhost:3003"),
		CoreEduServiceURL: getEnv("CORE_EDU_SERVICE_URL", "http://localhost:3004"),
		ContentServiceURL: getEnv("CONTENT_SERVICE_URL", "http://localhost:3005"),
		DataAnaServiceURL: getEnv("DATA_ANA_SERVICE_URL", "http://localhost:3006"),
		MsgServiceURL:     getEnv("MSG_SERVICE_URL", "http://localhost:3007"),
		AiServiceURL:      getEnv("AI_SERVICE_URL", "http://localhost:3008"),
		OTLPEndpoint:      getEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318"),
		LogLevel:          getEnv("LOG_LEVEL", "info"),
		DevMode:           devMode,
	}
}

// getEnv 读取环境变量，缺失时返回 fallback
func getEnv(key, fallback string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return fallback
}

// getEnvBool 读取环境变量并解析为 bool，缺失或解析失败时返回 fallback
func getEnvBool(key string, fallback bool) bool {
	if v := os.Getenv(key); v != "" {
		if b, err := strconv.ParseBool(v); err == nil {
			return b
		}
	}
	return fallback
}
