package strategy

import (
	"errors"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/common"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/schedulers/option"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/service/collector"
)

type DynamicResourcesStrategy struct {
	replicas  int32
	resources []*collector.ResourceStats
	opt       option.Option
}

func NewDynamicResourcesStrategy(resources []*collector.ResourceStats, opt option.Option, replica int32) *DynamicResourcesStrategy {
	return &DynamicResourcesStrategy{resources: resources, opt: opt, replicas: replica}
}

func (ps *DynamicResourcesStrategy) Schedule() ([]*AssignedCluster, error) {
	if ps.replicas < 1 {
		return nil, errors.New("replicas must be greater than 0")
	}

	switch ps.opt.GetOptionType() {
	case option.AI:
		opt := (interface{})(ps.opt).(*option.AiOption)

		var maxCardHoursAvailable float64
		var maxCpuCoreHoursAvailable float64
		var assignedCluster AssignedCluster
		var results []*AssignedCluster
		for _, res := range ps.resources {

			if res == nil {
				continue
			}

			if opt.ResourceType == "cpu" {
				if res.CpuCoreHours <= 0 {
					cluster := &AssignedCluster{ClusterId: res.ClusterId, Replicas: ps.replicas}
					results = append(results, cluster)
					return results, nil
				}

				if res.CpuCoreHours > maxCpuCoreHoursAvailable {
					maxCpuCoreHoursAvailable = res.CpuCoreHours
					assignedCluster.ClusterId = res.ClusterId
					assignedCluster.Replicas = ps.replicas
				}
			}

			if opt.ResourceType == "computeCard" {
				var maxCurrentCardHours float64
				for _, card := range res.CardsAvail {
					cardHours := common.RoundFloat( /*card.TOpsAtFp16**/ card.CardHours, 3)
					if cardHours > maxCurrentCardHours {
						maxCurrentCardHours = cardHours
					}
				}
				if maxCurrentCardHours > maxCardHoursAvailable {
					maxCardHoursAvailable = maxCurrentCardHours
					assignedCluster.ClusterId = res.ClusterId
					assignedCluster.Replicas = ps.replicas
				}
			}
		}
		results = append(results, &assignedCluster)
		return results, nil
	case option.CLOUD:

	}

	return nil, errors.New("failed to apply DynamicResourcesStrategy")
}
