package config

import (
	"os"
	"strings"
)

// Config holds Platform Bridge configuration.
type Config struct {
	Port           string
	Env            string
	GatewayURL     string
	AICoreURL      string
	InternalToken  string

	// Platform-specific.
	OBv11BotPort        string // port for OBv11 reverse WebSocket
	TelegramToken       string // Telegram Bot API token
	TelegramWebhookURL  string // public webhook URL for Telegram

	// Silent observation mode.
	PlatformSilentEnabled bool     // PLATFORM_SILENT_ENABLED, default true
	AdminNickname         string   // ADMIN_NICKNAME, admin's Cyrene identity nickname (default "开拓者")
	AdminNicknames         []string // ADMIN_NICKNAMES, default ["开拓者"]
	AdminMentionKeywords   []string // ADMIN_MENTION_KEYWORDS, default ["昔涟","Cyrene","管理员"]

	// Message sending.
	MessageSendIntervalMs int // MSG_SEND_INTERVAL_MS, minimum interval between platform messages (default 2000)
}

func Load() *Config {
	cfg := &Config{
		Port:          "8095",
		Env:           "development",
		GatewayURL:    "http://localhost:8080",
		AICoreURL:     "http://localhost:8081",
		OBv11BotPort:  "8096",
	}
	if v := os.Getenv("PORT"); v != "" {
		cfg.Port = v
	}
	if v := os.Getenv("ENV"); v != "" {
		cfg.Env = v
	}
	if v := os.Getenv("GATEWAY_URL"); v != "" {
		cfg.GatewayURL = v
	}
	if v := os.Getenv("AI_CORE_URL"); v != "" {
		cfg.AICoreURL = v
	}
	if v := os.Getenv("INTERNAL_SERVICE_TOKEN"); v != "" {
		cfg.InternalToken = v
	}
	if v := os.Getenv("OBV11_BOT_PORT"); v != "" {
		cfg.OBv11BotPort = v
	}
	if v := os.Getenv("TELEGRAM_BOT_TOKEN"); v != "" {
		cfg.TelegramToken = v
	}
	if v := os.Getenv("TELEGRAM_WEBHOOK_URL"); v != "" {
		cfg.TelegramWebhookURL = v
	}
	// Silent observation defaults.
	cfg.PlatformSilentEnabled = getEnvBool("PLATFORM_SILENT_ENABLED", true)
	cfg.AdminNickname = os.Getenv("ADMIN_NICKNAME")
	if cfg.AdminNickname == "" {
		cfg.AdminNickname = "开拓者"
	}
	cfg.AdminNicknames = getEnvList("ADMIN_NICKNAMES", []string{"开拓者"})
	cfg.AdminMentionKeywords = getEnvList("ADMIN_MENTION_KEYWORDS", []string{"昔涟", "Cyrene", "管理员"})
	cfg.MessageSendIntervalMs = getEnvInt("MSG_SEND_INTERVAL_MS", 2000)

	return cfg
}

func getEnvBool(key string, defaultVal bool) bool {
	v := os.Getenv(key)
	if v == "" {
		return defaultVal
	}
	return v == "true" || v == "1" || v == "yes"
}

func getEnvInt(key string, defaultVal int) int {
	v := os.Getenv(key)
	if v == "" {
		return defaultVal
	}
	n := 0
	for _, c := range v {
		if c >= '0' && c <= '9' {
			n = n*10 + int(c-'0')
		} else {
			return defaultVal
		}
	}
	return n
}

func getEnvList(key string, defaultVal []string) []string {
	v := os.Getenv(key)
	if v == "" {
		return defaultVal
	}
	parts := strings.Split(v, ",")
	result := make([]string, 0, len(parts))
	for _, p := range parts {
		p = strings.TrimSpace(p)
		if p != "" {
			result = append(result, p)
		}
	}
	if len(result) == 0 {
		return defaultVal
	}
	return result
}
