package apps

import (
	"context"
	"github.com/labstack/echo/v4"
	"mylomen_server/common/constant"
	"mylomen_server/common/dto"
	"mylomen_server/common/utils"
	"mylomen_server/infrastructure/remote_http"
	"mylomen_server/infrastructure/repository"
	"net/http"
)

func InitAiGroup(g *echo.Group) {
	g.POST("completions", func(c echo.Context) error {
		req := new(dto.AiReq)
		if err := c.Bind(req); err != nil {
			return c.JSON(500, err)
		}

		corpId := c.Get(constant.CorpId).(uint64)
		bizId := c.Get(constant.BizId).(uint64)
		uid := c.Get(constant.UID).(uint64)

		ctx := context.WithValue(context.Background(), constant.DBKey, repository.Db)

		//groupId
		key := utils.ToString(corpId) + "_" + utils.ToString(bizId) + "_" + utils.ToString(uid)
		groupId := utils.GetCache(key)
		result, err := remote_http.AiApi.Completions(ctx, req.Prompt, groupId)
		if err != nil || result == nil {
			return c.JSON(http.StatusOK, utils.Failed(err.Error()))
		}

		//缓存
		groupId = result.GroupId
		if groupId != "" {
			utils.PutCache(key, groupId)
		} else {
			utils.Clear(key)
		}

		return c.JSON(http.StatusOK, utils.Ok(result.Completions))
	})

	g.POST("completionsTest", func(c echo.Context) error {
		req := new(dto.AiReq)
		if err := c.Bind(req); err != nil {
			return c.JSON(500, err)
		}

		result, err := remote_http.AiOpenRouter.Completions(context.Background(), req.Prompt, "")
		if err != nil || result == nil {
			return c.JSON(http.StatusOK, utils.Failed(err.Error()))
		}

		return c.JSON(http.StatusOK, utils.Ok(result.Completions))
	})

}