package llm

import (
	"errors"
	"sort"
	"strings"
)

const secretReplacement = "[REDACTED]"

// RedactSecrets replaces configured secret values in diagnostics.
func RedactSecrets(message string, secrets []string) string {
	if message == "" || len(secrets) == 0 {
		return message
	}

	normalized := normalizeSecrets(secrets)
	for _, secret := range normalized {
		message = strings.ReplaceAll(message, secret, secretReplacement)
	}
	return message
}

// ErrorWithSecretsRedacted returns an error with known secret values removed
// from its message.
func ErrorWithSecretsRedacted(err error, secrets []string) error {
	if err == nil {
		return nil
	}
	return errors.New(RedactSecrets(err.Error(), secrets))
}

func normalizeSecrets(secrets []string) []string {
	seen := make(map[string]struct{}, len(secrets))
	result := make([]string, 0, len(secrets))
	for _, secret := range secrets {
		secret = strings.TrimSpace(secret)
		if secret == "" {
			continue
		}
		if _, ok := seen[secret]; ok {
			continue
		}
		seen[secret] = struct{}{}
		result = append(result, secret)
	}

	sort.Slice(result, func(i, j int) bool {
		return len(result[i]) > len(result[j])
	})
	return result
}
