package hpc

import (
	"context"
	"fmt"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/service"

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

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

type GetHpcTaskLogLogic struct {
	logx.Logger
	ctx        context.Context
	svcCtx     *svc.ServiceContext
	hpcService *service.HpcService
}

// 超算任务日志
func NewGetHpcTaskLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetHpcTaskLogLogic {
	cache := make(map[string]interface{}, 10)
	hpcService, err := service.NewHpcService(&svcCtx.Config, svcCtx.Scheduler.HpcStorages, cache)
	if err != nil {
		return nil
	}
	return &GetHpcTaskLogLogic{
		Logger:     logx.WithContext(ctx),
		ctx:        ctx,
		svcCtx:     svcCtx,
		hpcService: hpcService,
	}
}

func (l *GetHpcTaskLogLogic) GetHpcTaskLog(req *types.HpcTaskLogReq) (resp interface{}, err error) {
	var hpcR TaskHPCResult
	tx := l.svcCtx.DbEngin.Raw(
		"SELECT t.id, hpc.job_id ,hpc.adapter_id ,hpc.cluster_id FROM task t "+
			"INNER JOIN task_hpc hpc ON t.id = hpc.task_id "+
			"WHERE adapter_type_dict = 2 AND t.id = ?",
		req.TaskId,
	).Scan(&hpcR).Error
	if tx != nil {
		return nil, fmt.Errorf("数据库查询失败: %v", tx.Error)
	}
	if hpcR.ID == 0 {
		return nil, fmt.Errorf("任务不存在")
	}
	var adapterInfo types.AdapterInfo
	l.svcCtx.DbEngin.Raw("SELECT * FROM `t_adapter` where id = ?", hpcR.AdapterId).Scan(&adapterInfo)
	if adapterInfo.Id == "" {
		return nil, fmt.Errorf("adapter not found")
	}
	// 取消作业
	resp, err = l.hpcService.HpcExecutorAdapterMap[adapterInfo.Id].GetTaskLogs(l.ctx, hpcR.JobID, hpcR.ClusterId)
	if err != nil {
		return nil, err
	}

	return resp, nil
}
