package inference

import (
	"context"
	"github.com/pkg/errors"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"

	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetDeployTasksByTypeLogic) GetDeployTasksByType(req *types.GetDeployTasksByTypeReq) (resp *types.GetDeployTasksByTypeResp, err error) {
	resp = &types.GetDeployTasksByTypeResp{}

	list, err := l.svcCtx.Scheduler.AiStorages.GetDeployTaskListByType(req.ModelType)
	if err != nil {
		return nil, err
	}

	if len(list) == 0 {
		return nil, errors.New("实列不存在")
	}

	listcopy := make([]*models.AiDeployInstanceTask, len(list))
	copy(listcopy, list)

	for _, task := range list {
		inslist, err := l.svcCtx.Scheduler.AiStorages.GetInstanceListByDeployTaskId(task.Id)
		if err != nil {
			return nil, err
		}
		if len(inslist) == 0 {
			removeItem(&listcopy, task.Id)
		}
		var count int
		for _, ins := range inslist {
			if ins.Status == constants.Running {
				count++
			}
		}
		if count >= 1 {
			continue
		}

		removeItem(&listcopy, task.Id)
	}

	resp.List = listcopy
	return resp, nil
}

func removeItem(items *[]*models.AiDeployInstanceTask, id int64) {
	if len(*items) == 0 {
		return
	}
	for i := len(*items) - 1; i >= 0; i-- {
		if (*items)[i].Id == id {
			*items = append((*items)[:i], (*items)[i+1:]...)
		}
	}
}
