package web

import (
	"get-container/cmd/opsflow/backend"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

var (
	globalCfg *viper.Viper = nil
)

func Init(cfg *viper.Viper) {
	globalCfg = cfg
}

type RestfulResult struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data,omitempty"`
}

func ReturnGin(ctx *gin.Context, data any, err error) {
	if err != nil {
		ctx.JSON(500, RestfulResult{
			Code: 500,
			Msg:  err.Error(),
		})
		return
	}
	ctx.JSON(200, RestfulResult{
		Code: 200,
		Msg:  "ok",
		Data: data,
	})
}

func WebServer(addr string) error {
	engine := gin.Default()
	cmdGroup := engine.Group("/api/cmd")
	cmdGroup.GET("/all", func(ctx *gin.Context) {
		olu, err := backend.GetOnlineUser()
		if err != nil {
			ReturnGin(ctx, nil, err)
		}
		sys, err := backend.GetSysLoad()
		if err != nil {
			ReturnGin(ctx, nil, err)
		}
		dcu, err := backend.GetDCULoad()
		if err != nil {
			ReturnGin(ctx, nil, err)
		}
		ReturnGin(ctx, backend.AllInfo{
			DCUInfo:        dcu,
			SysInfo:        *sys,
			OnlineUserInfo: olu,
		}, err)
	})
	cmdGroup.GET("/loginUser", func(ctx *gin.Context) {
		olu, err := backend.GetOnlineUser()
		ReturnGin(ctx, olu, err)
	})
	cmdGroup.GET("/sysload", func(ctx *gin.Context) {
		sys, err := backend.GetSysLoad()
		ReturnGin(ctx, sys, err)
	})
	cmdGroup.GET("/dcuload", func(ctx *gin.Context) {
		dcu, err := backend.GetDCULoad()
		ReturnGin(ctx, dcu, err)
	})
	cmdGroup.GET("/rcclinfo", func(ctx *gin.Context) {
		_, r, err := backend.AllReducePerf(globalCfg.GetString("rccl_test_path"), globalCfg.GetStringSlice("rccl_all_reduce_perf_args")...)
		ReturnGin(ctx, r, err)
	})
	return engine.Run(addr)
}
