/*
Copyright 2024 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package alternatives

import (
	"fmt"
	"regexp"

	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider"
	"k8s.io/autoscaler/cluster-autoscaler/config"
	"k8s.io/autoscaler/cluster-autoscaler/expander"
	"k8s.io/autoscaler/cluster-autoscaler/simulator/framework"
	"k8s.io/klog/v2"
)

type alternatives struct {
}

// NewFilter returns an expansion filter that picks non-alternative node groups.
func NewFilter() expander.Filter {
	return &alternatives{}
}

func (a *alternatives) BestOptions(options []expander.Option, nodeInfo map[string]*framework.NodeInfo) []expander.Option {
	var alters []string
	for _, opt := range options {
		if o, err := opt.NodeGroup.GetOptions(config.NodeGroupAutoscalingOptions{}); err == nil {
			if o.Alternative != "" {
				alters = append(alters, o.Alternative)
			}
		}
	}
	var bestOptions []expander.Option
	for _, opt := range options {
		if !isAlternativeNodeGroup(opt.NodeGroup, alters) {
			bestOptions = append(bestOptions, opt)
		}
	}
	if len(bestOptions) == 0 {
		klog.V(4).Infof("No non-alternative node groups found, using all options")
		return options
	}
	return bestOptions
}

func isAlternativeNodeGroup(nodeGroup cloudprovider.NodeGroup, alternatives []string) bool {
	for _, alter := range alternatives {
		if NodeGroupMatchesOption(nodeGroup, alter) {
			return true
		}
	}
	return false
}

// NodeGroupMatchesOption checks if a node group matches an option
// It can be either strict match or have optional prefix and uuid style suffix.
func NodeGroupMatchesOption(nodeGroup cloudprovider.NodeGroup, opt string) bool {
	if nodeGroup.Id() == opt {
		return true
	}
	reg, err := regexp.Compile(fmt.Sprintf(`^([a-zA-Z0-9]+-)?%s(-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})?$`, opt))
	return err == nil && reg.MatchString(nodeGroup.Id())
}
