package capacitycontroller

import (
	"errors"
	"os"
	"strings"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/config"
)

func NewConfiguredAdapter(cfg config.Config) (OrchestratorAdapter, error) {
	switch strings.ToLower(strings.TrimSpace(cfg.CapacityOrchestratorAdapter)) {
	case "static":
		pools, err := cfg.CapacityPools()
		if err != nil {
			return nil, err
		}
		initial := make(map[string]int, len(pools))
		for _, pool := range pools {
			initial[pool.ID] = pool.BootstrapReplicas
		}
		return NewStaticAdapter(initial), nil
	case "", "kubernetes":
		return NewKubernetesClient(KubernetesConfig{
			Namespace: adapterEnv("AI_GATEWAY_CAPACITY_CONTROLLER_NAMESPACE", adapterEnv("POD_NAMESPACE", "easyai")),
			APIServer: adapterEnv("AI_GATEWAY_CAPACITY_CONTROLLER_API_SERVER", "https://kubernetes.default.svc"),
			TokenFile: adapterEnv("AI_GATEWAY_CAPACITY_CONTROLLER_TOKEN_FILE", "/var/run/secrets/kubernetes.io/serviceaccount/token"),
			CAFile:    adapterEnv("AI_GATEWAY_CAPACITY_CONTROLLER_CA_FILE", "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"),
		})
	default:
		return nil, errors.New("unsupported capacity orchestrator adapter")
	}
}

func adapterEnv(name, fallback string) string {
	if value := strings.TrimSpace(os.Getenv(name)); value != "" {
		return value
	}
	return fallback
}
