package envcompat

import (
	"log/slog"
	"os"
	"strings"
	"sync"
)

var warnOnce sync.Once

// WarnLegacy reports each Registry alias whose preferred name is unset but at
// least one legacy name is still set. Pure function; safe to call repeatedly.
func WarnLegacy(emit func(legacyName, newName string)) {
	for _, alias := range Registry {
		if hasNonEmptyEnv(alias.New) {
			continue
		}
		for _, legacy := range alias.Legacy {
			if hasNonEmptyEnv(legacy) {
				emit(legacy, alias.New)
			}
		}
	}
}

// WarnLegacyOnce is WarnLegacy wrapped in sync.Once so multiple entry points
// (e.g. tests + main) can call it safely. Logs via slog.
func WarnLegacyOnce(log *slog.Logger) {
	warnOnce.Do(func() {
		WarnLegacy(func(legacyName, newName string) {
			if log == nil {
				return
			}
			log.Warn("env var renamed; please migrate",
				"legacy_name", legacyName,
				"new_name", newName,
			)
		})
	})
}

func hasNonEmptyEnv(name string) bool {
	v, ok := os.LookupEnv(name)
	return ok && strings.TrimSpace(v) != ""
}
