package chat

import (
	"context"
	"errors"

	"wechat-api/ent"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/compapi"
	"wechat-api/internal/utils/contextkey"

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

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

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

func (l *ChatCompletionsLogic) ChatCompletions(req *types.CompApiReq) (resp *types.CompOpenApiResp, err error) {
	// todo: add your logic here and delete this line

	/*
	   1.鉴权获得token
	   2.必要参数检测及转换
	   3. 根据event_type选择不同处理路由
	*/
	var (
		apiKeyObj *ent.ApiKey
		ok        bool
	)
	workToken := compapi.GetWorkTokenByID(req.EventType, req.WorkId)
	apiKeyObj, ok = contextkey.AuthTokenInfoKey.GetValue(l.ctx)
	if !ok {
		return nil, errors.New("content get token err")
	}
	/*
		fmt.Println("=========================================")
		fmt.Printf("In ChatCompletion Get Token Info:\nKey:'%s'\n", apiKeyObj.Key)
		fmt.Printf("Title:'%s'\n", apiKeyObj.Title)
		fmt.Printf("OpenaiBase:'%s'\n", apiKeyObj.OpenaiBase)
		fmt.Printf("OpenaiKey:'%s'\n", apiKeyObj.OpenaiKey)
		fmt.Printf("workToken:'%s' because %s/%s\n", workToken, req.EventType, req.WorkId)
		fmt.Println("=========================================")
	*/

	if len(apiKeyObj.OpenaiBase) == 0 || len(workToken) == 0 {
		return nil, errors.New("not auth info")
	}
	return l.workForFastgpt(req, workToken, apiKeyObj.OpenaiBase)
}

func (l *ChatCompletionsLogic) workForFastgpt(req *types.CompApiReq, apiKey string, apiBase string) (resp *types.CompOpenApiResp, err error) {

	//apiKey := "fastgpt-d2uehCb2T40h9chNGjf4bpFrVKmMkCFPbrjfVLZ6DAL2zzqzOFJWP"
	return compapi.NewFastgptChatCompletions(l.ctx, apiKey, apiBase, req)

}
