package config

import (
	"os"
	"strconv"
	"strings"
)

type Config struct {
	HTTPPort      string
	MQTTBroker    string
	MQTTUsername  string
	MQTTPassword  string
	MQTTClientID  string
	MQTTSubscribe string
	MQTTQOS       byte
	SQLitePath    string
	TTLDays       int
	MQTTDebug     bool
	SettingsFile  string
	SysSubscribe  string
}

func Load() Config {
	cfg := Config{
		HTTPPort:      getEnv("PORT", "8088"),
		MQTTBroker:    getEnv("MQTT_BROKER", "tcp://broker.hivemq.com:1883"),
		MQTTUsername:  getEnv("MQTT_USERNAME", ""),
		MQTTPassword:  getEnv("MQTT_PASSWORD", ""),
		MQTTClientID:  getEnv("MQTT_CLIENT_ID", "mqtt-web-explorer"),
		MQTTSubscribe: getEnv("MQTT_SUBSCRIBE", "#"),
		SQLitePath:    getEnv("SQLITE_DB", "./data/mqtt.db"),
		TTLDays:       getEnvInt("TTL_DAYS", 7),
		MQTTQOS:       byte(getEnvInt("MQTT_QOS", 0)),
		MQTTDebug:     getEnvBool("MQTT_DEBUG", false),
		SettingsFile:  getEnv("SETTINGS_FILE", "/data/settings.yml"),
		SysSubscribe:  getEnv("MQTT_SYS_SUBSCRIBE", "$SYS/#"),
	}

	return cfg
}

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

func getEnvInt(key string, fallback int) int {
	val := os.Getenv(key)
	if val == "" {
		return fallback
	}
	parsed, err := strconv.Atoi(val)
	if err != nil {
		return fallback
	}
	return parsed
}

func getEnvBool(key string, fallback bool) bool {
	val := os.Getenv(key)
	if val == "" {
		return fallback
	}
	switch strings.ToLower(val) {
	case "1", "true", "yes", "on":
		return true
	case "0", "false", "no", "off":
		return false
	default:
		return fallback
	}
}
