package inference

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

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

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

func (l *StartDeployInstanceListLogic) StartDeployInstanceList(req *types.StartDeployInstanceReq) (resp *types.StartDeployInstanceResp, err error) {
	resp = &types.StartDeployInstanceResp{}

	id, err := strconv.ParseInt(req.Id, 10, 64)
	ins, err := l.svcCtx.Scheduler.AiStorages.GetInferDeployInstanceById(id)
	if err != nil {
		return nil, err
	}

	in, err := l.svcCtx.Scheduler.AiService.InferenceAdapterMap[strconv.FormatInt(ins.AdapterId, 10)][strconv.FormatInt(ins.ClusterId, 10)].GetInferDeployInstance(l.ctx, ins.InstanceId)
	if err != nil {
		return nil, err
	}

	if status.CheckStopStatus(in) {
		success := l.svcCtx.Scheduler.AiService.InferenceAdapterMap[req.AdapterId][req.ClusterId].StartInferDeployInstance(l.ctx, in.InstanceId)
		if !success {
			return nil, errors.New("start instance failed")
		}
	}

	ins.Status = "Updating"
	err = l.svcCtx.Scheduler.AiStorages.UpdateInferDeployInstance(ins, true)
	if err != nil {
		return nil, err
	}

	return resp, nil
}
