// Package config provides application configuration loaded from environment
// variables with sensible defaults for local development.
package config

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

// Config holds all application configuration.
type Config struct {
	Port                      int
	DatabaseURL               string
	CORSOrigin                string
	LogLevel                  string
	Environment               string
	GatewayRestURL            string
	GatewayRestPollInterval   time.Duration
	WSGatewayURL              string
	WSGatewayToken            string
}

// Load reads configuration from environment variables, applying defaults where
// values are not set. All secrets come from the environment — nothing is hardcoded.
func Load() *Config {
	return &Config{
		Port:                      getEnvInt("PORT", 8080),
		DatabaseURL:               getEnv("DATABASE_URL", "postgres://controlcenter:controlcenter@localhost:5432/controlcenter?sslmode=disable"),
		CORSOrigin:                getEnv("CORS_ORIGIN", "*"),
		LogLevel:                  getEnv("LOG_LEVEL", "info"),
		Environment:               getEnv("ENVIRONMENT", "development"),
		GatewayRestURL:            getEnv("GATEWAY_URL", "http://host.docker.internal:18789/api/agents"),
		GatewayRestPollInterval:   getEnvDuration("GATEWAY_POLL_INTERVAL", 5*time.Second),
		WSGatewayURL:              getEnv("WS_GATEWAY_URL", "ws://host.docker.internal:18789/"),
		WSGatewayToken:            getEnv("OPENCLAW_GATEWAY_TOKEN", ""),
	}
}

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

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

func getEnvDuration(key string, fallback time.Duration) time.Duration {
	if v := os.Getenv(key); v != "" {
		if d, err := time.ParseDuration(v); err == nil {
			return d
		}
	}
	return fallback
}