package config

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

type Config struct {
	Host                 string
	Port                 int
	SocketPath           string
	HeartbeatIntervalSec int
	HeartbeatWaitSec     int
	WSOriginPatterns     []string
	WorkerSocketURL      string
}

func Load() Config {
	return Config{
		Host:                 getenv("ALT_API_HOST", "127.0.0.1"),
		Port:                 getenvInt("ALT_API_PORT", 8080),
		SocketPath:           getenv("ALT_API_SOCKET_PATH", "/socket"),
		HeartbeatIntervalSec: getenvInt("ALT_SOCKET_HEARTBEAT_INTERVAL_SEC", 30),
		HeartbeatWaitSec:     getenvInt("ALT_SOCKET_HEARTBEAT_WAIT_SEC", 10),
		WSOriginPatterns:     getenvList("ALT_API_WS_ORIGIN_PATTERNS", "localhost:*,127.0.0.1:*"),
		WorkerSocketURL:      getenv("ALT_WORKER_SOCKET_URL", "ws://127.0.0.1:8081/socket"),
	}
}

func getenv(key, fallback string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return fallback
}

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

func getenvList(key string, fallback string) []string {
	value := getenv(key, fallback)
	parts := strings.Split(value, ",")
	items := make([]string, 0, len(parts))
	for _, part := range parts {
		item := strings.TrimSpace(part)
		if item != "" {
			items = append(items, item)
		}
	}
	return items
}
