package cmd

import (
	"strings"

	"github.com/spf13/cobra"

	"git.secluded.site/keld/internal/config"
)

// completePreset offers completions for the root --preset flag.
func completePreset(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) {
	if strings.Contains(toComplete, "@") {
		return completeSuffix(toComplete), cobra.ShellCompDirectiveNoFileComp
	}

	prefixes := config.Prefixes()
	presets := config.Presets()

	seen := make(map[string]struct{}, len(prefixes)+len(presets))
	out := make([]string, 0, len(prefixes)+len(presets))

	add := func(s string) {
		if !strings.HasPrefix(s, toComplete) {
			return
		}
		if _, ok := seen[s]; ok {
			return
		}
		seen[s] = struct{}{}
		out = append(out, s)
	}

	for _, p := range prefixes {
		add(p)
	}
	for _, p := range presets {
		add(p)
	}

	return out, cobra.ShellCompDirectiveNoFileComp
}

// completeSuffix generates completions when the user has typed a prefix
// containing "@". For example, typing "home@" offers "home@cloud",
// "home@nas", etc. by combining the typed prefix with known suffixes.
func completeSuffix(typed string) []string {
	idx := strings.Index(typed, "@")
	if idx < 0 {
		return nil
	}

	prefix := typed[:idx+1] // e.g. "home@"
	suffixes := config.Suffixes()

	out := make([]string, 0, len(suffixes))
	for _, sfx := range suffixes {
		// sfx is e.g. "@cloud"; combine as "home@cloud".
		combo := prefix[:len(prefix)-1] + sfx
		if strings.HasPrefix(combo, typed) {
			out = append(out, combo)
		}
	}
	return out
}
