package deploy

import (
	"fmt"
	"strings"
)

var allowedRegistryPathPrefixes = []string{
	`software\`,
	`environment`,
}

// ParseRegistryHive maps operator hive strings to internal tokens (hkcu/hklm).
func ParseRegistryHive(hive string) (string, error) {
	switch strings.ToUpper(strings.TrimSpace(hive)) {
	case "HKCU", "HKEY_CURRENT_USER", "CURRENT_USER":
		return "hkcu", nil
	case "HKLM", "HKEY_LOCAL_MACHINE", "LOCAL_MACHINE":
		return "hklm", nil
	default:
		return "", fmt.Errorf("unsupported hive %q (use HKCU or HKLM)", hive)
	}
}

// ValidateRegistryPath ensures fleet registry ops stay under safe prefixes.
func ValidateRegistryPath(hiveToken, subkey string) error {
	subkey = strings.TrimSpace(subkey)
	subkey = strings.TrimPrefix(subkey, `\`)
	subkey = strings.TrimSuffix(subkey, `\`)
	if subkey == "" {
		return fmt.Errorf("registry path is required")
	}
	lower := strings.ToLower(subkey)
	for _, prefix := range allowedRegistryPathPrefixes {
		if strings.HasPrefix(lower, prefix) {
			return nil
		}
	}
	return fmt.Errorf("registry path %q is outside the allowed prefix list (Software\\, Environment)", subkey)
}
