package pack

import "strings"

func ResolveApplicableHostOverlays(provider ProviderManifest, targetHost string, hostVersion string) ([]HostOverlay, error) {
	trimmedTargetHost := strings.TrimSpace(targetHost)
	trimmedHostVersion := strings.TrimSpace(hostVersion)
	if trimmedTargetHost == "" || trimmedHostVersion == "" || len(provider.HostOverlays) == 0 {
		return nil, nil
	}
	result := make([]HostOverlay, 0, len(provider.HostOverlays))
	for _, overlay := range provider.HostOverlays {
		if !strings.EqualFold(strings.TrimSpace(overlay.TargetHost), trimmedTargetHost) {
			continue
		}
		ok, err := hostOverlayMatchesVersion(overlay, trimmedHostVersion)
		if err != nil {
			return nil, err
		}
		if ok {
			result = append(result, overlay)
		}
	}
	return result, nil
}

func hostOverlayMatchesVersion(overlay HostOverlay, hostVersion string) (bool, error) {
	minVersion := strings.TrimSpace(overlay.MinHostVersion)
	if minVersion != "" {
		cmp, err := compareVersions(hostVersion, minVersion)
		if err != nil {
			return false, err
		}
		if cmp < 0 {
			return false, nil
		}
	}
	maxVersion := strings.TrimSpace(overlay.MaxHostVersion)
	if maxVersion != "" {
		ok, err := matchesMaxConstraint(hostVersion, maxVersion)
		if err != nil {
			return false, err
		}
		if !ok {
			return false, nil
		}
	}
	return true, nil
}
