package config

import (
	"os"
	"strconv"
)

type Config struct {
	AppEnv                   string
	HTTPAddr                 string
	DatabaseURL              string
	RedisURL                 string
	ProtoSocketPath          string
	ProtoSocketHeartbeatSec  int
	ProtoSocketHeartbeatWait int
	ForgejoWebhookSecret     string
	WorkerEnabled            bool
	// IOPEndpoint is the base URL of the IOP HTTP dispatch service.
	// When empty, agent_run operations are not picked.
	IOPEndpoint string
}

func Load() Config {
	return Config{
		AppEnv:                   getEnv("APP_ENV", "local"),
		HTTPAddr:                 getEnv("HTTP_ADDR", ":8080"),
		DatabaseURL:              os.Getenv("DATABASE_URL"),
		RedisURL:                 os.Getenv("REDIS_URL"),
		ProtoSocketPath:          getEnv("PROTO_SOCKET_PATH", "/proto-socket"),
		ProtoSocketHeartbeatSec:  getEnvInt("PROTO_SOCKET_HEARTBEAT_SEC", 30),
		ProtoSocketHeartbeatWait: getEnvInt("PROTO_SOCKET_HEARTBEAT_WAIT_SEC", 10),
		ForgejoWebhookSecret:     os.Getenv("FORGEJO_WEBHOOK_SECRET"),
		WorkerEnabled:            getEnvBool("WORKER_ENABLED", true),
		IOPEndpoint:              os.Getenv("IOP_ENDPOINT"),
	}
}

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

func getEnvBool(key string, fallback bool) bool {
	value := os.Getenv(key)
	if value == "" {
		return fallback
	}
	parsed, err := strconv.ParseBool(value)
	if err != nil {
		return fallback
	}
	return parsed
}

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
}
