package config

import (
	"os"
	"path/filepath"
	"sort"
	"strings"
)

// DefaultConfigDirs lists the base directories searched for config files,
// in ascending priority order.
var DefaultConfigDirs = []string{
	"/usr/share/keld",
	"/etc/keld",
	"~/.config/keld",
}

// DiscoverFiles returns config file paths in ascending priority order.
//
// The search order is:
//  1. For each directory in DefaultConfigDirs: config.toml, then sorted conf.d/*.toml
//  2. Paths/globs from the KELD_CONFIG_PATHS env var (colon-separated)
//  3. If KELD_CONFIG_FILE is set, it replaces ALL of the above
//
// All paths support ~ (home dir) and $VAR expansion.
func DiscoverFiles() []string {
	return discoverFiles(os.Getenv)
}

// discoverFiles is the testable core; getenv abstracts os.Getenv.
func discoverFiles(getenv func(string) string) []string {
	if single := getenv("KELD_CONFIG_FILE"); single != "" {
		return []string{ExpandPath(single)}
	}

	var paths []string

	for _, dir := range DefaultConfigDirs {
		dir = ExpandPath(dir)

		paths = append(paths, filepath.Join(dir, "config.toml"))
		paths = append(paths, sortedGlob(filepath.Join(dir, "conf.d", "*.toml"))...)
	}

	if extra := getenv("KELD_CONFIG_PATHS"); extra != "" {
		for _, entry := range strings.Split(extra, ":") {
			entry = ExpandPath(strings.TrimSpace(entry))
			if strings.ContainsAny(entry, "*?[") {
				paths = append(paths, sortedGlob(entry)...)
			} else {
				paths = append(paths, entry)
			}
		}
	}

	return paths
}

// ExpandPath expands ~ to the user's home directory and $VAR references.
func ExpandPath(p string) string {
	if strings.HasPrefix(p, "~/") || p == "~" {
		home, err := os.UserHomeDir()
		if err == nil {
			p = home + p[1:]
		}
	}
	return os.ExpandEnv(p)
}

// sortedGlob returns glob matches in sorted order, or nil on error.
func sortedGlob(pattern string) []string {
	matches, err := filepath.Glob(pattern)
	if err != nil || len(matches) == 0 {
		return nil
	}
	sort.Strings(matches)
	return matches
}
