package discovery

import "strings"

const kvEntryPrefix = "entry."

func registryEntryKey(entry RegistryEntry) string {
	return registryKey(entry.Service, entry.Rail, entry.Network, entry.Operations, entry.Version, entry.InstanceID)
}

func registryKey(service, rail, network string, operations []string, version, instanceID string) string {
	service = normalizeKeyPart(service)
	rail = normalizeKeyPart(rail)
	op := normalizeKeyPart(firstOperation(operations))
	version = normalizeKeyPart(version)
	instanceID = normalizeKeyPart(instanceID)
	if instanceID == "" {
		return ""
	}
	if service == "" {
		service = "service"
	}
	if rail == "" {
		rail = "none"
	}
	if op == "" {
		op = "none"
	}
	if version == "" {
		version = "unknown"
	}
	parts := []string{service, rail, op, version, instanceID}
	if network != "" {
		netPart := normalizeKeyPart(network)
		if netPart != "" {
			parts = append(parts, netPart)
		}
	}
	return strings.Join(parts, ".")
}

func kvKeyFromRegistryKey(key string) string {
	key = strings.TrimSpace(key)
	if key == "" {
		return ""
	}
	if strings.HasPrefix(key, kvEntryPrefix) {
		return key
	}
	return kvEntryPrefix + key
}

func registryKeyFromKVKey(key string) string {
	key = strings.TrimSpace(key)
	if strings.HasPrefix(key, kvEntryPrefix) {
		return strings.TrimPrefix(key, kvEntryPrefix)
	}
	return key
}

func firstOperation(ops []string) string {
	for _, op := range ops {
		op = strings.TrimSpace(op)
		if op != "" {
			return op
		}
	}
	return ""
}

func normalizeKeyPart(value string) string {
	value = strings.ToLower(strings.TrimSpace(value))
	if value == "" {
		return ""
	}
	var b strings.Builder
	b.Grow(len(value))
	lastDash := false
	for _, r := range value {
		if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
			b.WriteRune(r)
			lastDash = false
			continue
		}
		if r == '-' || r == '_' {
			if !lastDash {
				b.WriteByte('-')
				lastDash = true
			}
			continue
		}
		if !lastDash {
			b.WriteByte('-')
			lastDash = true
		}
	}
	out := strings.Trim(b.String(), "-")
	return out
}
