package ai

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/service/utils/stat"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"
)

type GetCenterOverviewLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetCenterOverviewLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCenterOverviewLogic {
	return &GetCenterOverviewLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetCenterOverviewLogic) GetCenterOverview() (resp *types.CenterOverviewResp, err error) {
	resp = &types.CenterOverviewResp{}

	var centerNum int32
	var taskNum int32
	var cardNum int32
	var totalTops float64

	adapterList, err := l.svcCtx.Scheduler.AiStorages.GetAdaptersByType("1")
	if err != nil {
		return nil, err
	}
	centerNum = int32(len(adapterList))
	resp.CenterNum = centerNum

	go stat.UpdateClusterResources(l.svcCtx, adapterList)

	for _, adapter := range adapterList {
		taskList, err := l.svcCtx.Scheduler.AiStorages.GetAiTasksByAdapterId(adapter.Id)
		if err != nil {
			continue
		}
		taskNum += int32(len(taskList))
	}
	resp.TaskNum = taskNum

	for _, adapter := range adapterList {
		clusters, err := l.svcCtx.Scheduler.AiStorages.GetClustersByAdapterId(adapter.Id)
		if err != nil {
			continue
		}
		for _, cluster := range clusters.List {
			clusterResource, err := l.svcCtx.Scheduler.AiStorages.GetClusterResourcesById(cluster.Id)

			if err != nil {
				continue
			}
			cardNum += int32(clusterResource.CardTotal)
			totalTops += clusterResource.CardTopsTotal
		}
	}
	resp.CardNum = cardNum
	resp.PowerInTops = totalTops

	return resp, nil
}
