package config

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

type Config struct {
	Host           string
	Port           string
	DBPath         string
	DataDir        string
	PingInterval   int    // seconds
	SSHTimeout     int    // seconds
	LogLevel       string
	WebStaticPath  string
	AdminUser      string
	AdminPass      string
	SessionSecret  string
	LogRetentionDays int // 0 = keep forever
	UIRefreshInterval int // milliseconds, 0 = disable auto refresh
	EncryptKey        string // for AES password encryption
}

func Load() *Config {
	cfg := &Config{
		Host:           getEnv("HOST", "0.0.0.0"),
		Port:           getEnv("PORT", "8080"),
		DBPath:         getEnv("DB_PATH", "./data/lan-manager.db"),
		DataDir:        getEnv("DATA_DIR", "./data"),
		PingInterval:   getEnvInt("PING_INTERVAL", 60),
		SSHTimeout:     getEnvInt("SSH_TIMEOUT", 10),
		LogLevel:       getEnv("LOG_LEVEL", "info"),
		WebStaticPath:  getEnv("WEB_STATIC_PATH", ""),
		AdminUser:      getEnv("ADMIN_USER", "admin"),
		AdminPass:      getEnv("ADMIN_PASS", "admin"),
		SessionSecret:  getEnv("SESSION_SECRET", "lan-manager-secret-change-in-production"),
		LogRetentionDays: getEnvInt("LOG_RETENTION_DAYS", 0),
		UIRefreshInterval: getEnvInt("UI_REFRESH_INTERVAL", 10000),
		EncryptKey:        getEnv("ENCRYPT_KEY", ""),
	}

	if cfg.AdminPass == "admin" {
		log.Println("[WARN] Using default admin password. Please set ADMIN_PASS env variable in production.")
	}
	return cfg
}

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

func getEnvInt(key string, defaultValue int) int {
	v := os.Getenv(key)
	if v == "" {
		return defaultValue
	}
	n, err := strconv.Atoi(v)
	if err != nil {
		return defaultValue
	}
	return n
}
