package lib

import (
	"os"
	"strconv"
	"time"
)

// Config holds all configuration values
type Config struct {
	// Discord settings
	DiscordToken string

	// Himbucks settings
	HimbucksPerReward     int
	MessageCountThreshold int
	CooldownPeriod        time.Duration

	// Markov settings
	MarkovDefaultMessages int
	MarkovMaxMessages     int
	MarkovCacheSize       int
	MarkovMaxNGram        int  // Maximum n-gram level (3, 4, 5, etc.)
	MarkovMemoryLimit     int  // Memory limit in MB for n-gram chains

	// Database settings
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime time.Duration

	// Command cooldowns (in seconds)
	PingCooldown     int
	HsCooldown       int
	MarkovCooldown   int
	MarkovAskCooldown int
	HimbucksCooldown int
	HimboardCooldown int
	SendbucksCooldown int
}

var AppConfig *Config

// LoadConfig loads configuration from environment variables
func LoadConfig() *Config {
	config := &Config{
		// Discord settings
		DiscordToken: getEnv("DISCORD_TOKEN", ""),

		// Himbucks settings
		HimbucksPerReward:     getEnvInt("HIMBUCKS_PER_REWARD", 10),
		MessageCountThreshold: getEnvInt("MESSAGE_COUNT_THRESHOLD", 5),
		CooldownPeriod:        time.Duration(getEnvInt("HIMBUCKS_COOLDOWN_MINUTES", 1)) * time.Minute,

		// Markov settings
		MarkovDefaultMessages: getEnvInt("MARKOV_DEFAULT_MESSAGES", 100),
		MarkovMaxMessages:     getEnvInt("MARKOV_MAX_MESSAGES", 1000),
		MarkovCacheSize:       getEnvInt("MARKOV_CACHE_SIZE", 10),
		MarkovMaxNGram:         getEnvInt("MARKOV_MAX_NGRAM", 5),
		MarkovMemoryLimit:      getEnvInt("MARKOV_MEMORY_LIMIT_MB", 100),

		// Database settings
		MaxOpenConns:    getEnvInt("DB_MAX_OPEN_CONNS", 25),
		MaxIdleConns:    getEnvInt("DB_MAX_IDLE_CONNS", 5),
		ConnMaxLifetime: time.Duration(getEnvInt("DB_CONN_MAX_LIFETIME_MINUTES", 5)) * time.Minute,

		// Command cooldowns (in seconds)
		PingCooldown:      getEnvInt("PING_COOLDOWN_SECONDS", 5),
		HsCooldown:        getEnvInt("HS_COOLDOWN_SECONDS", 10),
		MarkovCooldown:    getEnvInt("MARKOV_COOLDOWN_SECONDS", 30),
		MarkovAskCooldown: getEnvInt("MARKOV_ASK_COOLDOWN_SECONDS", 30),
		HimbucksCooldown:  getEnvInt("HIMBUCKS_COOLDOWN_SECONDS", 5),
		HimboardCooldown:  getEnvInt("HIMBOARD_COOLDOWN_SECONDS", 5),
		SendbucksCooldown: getEnvInt("SENDBUCKS_COOLDOWN_SECONDS", 1800),
	}

	AppConfig = config
	return config
}

// getEnv gets an environment variable with a default value
func getEnv(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

// getEnvInt gets an environment variable as an integer with a default value
func getEnvInt(key string, defaultValue int) int {
	if value := os.Getenv(key); value != "" {
		if intValue, err := strconv.Atoi(value); err == nil {
			return intValue
		}
	}
	return defaultValue
} 