package registry

import (
	"fmt"
	"sort"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/store/model"
)

func MarshalJSONObject(value map[string]any, field string) ([]byte, error) {
	if value == nil {
		value = map[string]any{}
	}
	encoded, err := model.MarshalJSONObject("app "+field, value)
	if err != nil {
		return nil, fmt.Errorf("encode app %s: %w", field, err)
	}
	return encoded, nil
}

func OptionalStringSliceField(document map[string]any, key string) ([]string, error) {
	raw, exists := document[key]
	if !exists || raw == nil {
		return nil, nil
	}
	values, ok := raw.([]any)
	if !ok {
		return nil, fmt.Errorf("%s must be an array", key)
	}
	result := make([]string, 0, len(values))
	for _, value := range values {
		text, ok := value.(string)
		if !ok {
			return nil, fmt.Errorf("%s entries must be strings", key)
		}
		trimmed := strings.TrimSpace(text)
		if trimmed == "" {
			continue
		}
		result = append(result, trimmed)
	}
	return result, nil
}

func SortedUniqueScopes(scopes []string) []string {
	if len(scopes) == 0 {
		return []string{}
	}
	seen := make(map[string]struct{}, len(scopes))
	result := make([]string, 0, len(scopes))
	for _, scope := range scopes {
		trimmed := strings.TrimSpace(scope)
		if trimmed == "" {
			continue
		}
		if _, ok := seen[trimmed]; ok {
			continue
		}
		seen[trimmed] = struct{}{}
		result = append(result, trimmed)
	}
	sort.Strings(result)
	return result
}

func UniqueTrimmedStrings(values []string) []string {
	result := make([]string, 0, len(values))
	seen := make(map[string]struct{}, len(values))
	for _, value := range values {
		trimmed := strings.TrimSpace(value)
		if trimmed == "" {
			continue
		}
		if _, exists := seen[trimmed]; exists {
			continue
		}
		seen[trimmed] = struct{}{}
		result = append(result, trimmed)
	}
	return result
}
