package jcs

import (
	"encoding/json"
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"github.com/rs/zerolog/log"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/scheduler/database"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"
	"gitlink.org.cn/JointCloud/pcm-openi/common"
)

type JobStatusReportReq struct {
	Report interface{} `json:"report"`
}
type TrainReportMessage struct {
	Type      string `json:"type"`
	TaskName  string `json:"taskName"`
	TaskID    string `json:"taskID"`
	Status    bool   `json:"status"`
	Message   string `json:"message"`
	ClusterID string `json:"clusterID"`
	Output    string `json:"output"`
}
type InferReportMessage struct {
	Type       string `json:"type"`
	TaskName   string `json:"taskName"`
	TaskID     string `json:"taskID"`
	Status     bool   `json:"status"`
	Message    string `json:"message"`
	Url        string `json:"url"`
	ID         string `json:"id"`
	AdapterID  string `json:"adapterId"`
	ClusterID  string `json:"clusterId"`
	InstanceID string `json:"instanceId"`
}

func StatusReport(url string, report interface{}) error {
	resp := struct {
		Code string `json:"code"`
		Msg  string `json:"message"`
		Data string `json:"data"`
	}{}

	req := common.GetRestyRequest(common.TIMEOUT)
	rp, err := req.
		SetHeader("Content-Type", "application/json").
		SetBody(report).
		SetResult(&resp).
		Post(url)

	bodyStr, _ := jsoniter.MarshalToString(report)
	log.Debug().Msgf("上报任务状态到中间件,请求url：%s, 请求参数：%s, 响应结果：%s", url, bodyStr, string(rp.Body()))

	if err != nil {
		logx.Errorf("############ Report Status Message Error %s", err.Error())

		return err
	}
	if resp.Code != "OK" {
		logx.Errorf("############ Report Status Message After Sending %s", string(rp.Body()))
		return fmt.Errorf("report status message failed: %s", resp.Msg)
	}

	return nil
}

func TempSaveReportToTask(store *database.AiStorage, task *types.TaskModel, report interface{}) error {
	jsonBytes, err := json.Marshal(report)

	task.Result = string(jsonBytes)

	err = store.UpdateTask(task)
	if err != nil {
		return err
	}

	return nil
}
