package compapi

import (
	"errors"
	"fmt"
	"net/http"
	"wechat-api/ent"
	"wechat-api/internal/types"

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
)

type StdClient struct {
	*Client
}

func (me *StdClient) CallbackPrepare(params any) ([]byte, error) {
	taskData, ok := params.(*ent.CompapiAsynctask)
	if !ok {
		return nil, errors.New("invalid callback taskdata")
	}
	return AnyToBytes(taskData.ResponseRaw)
}

func (me *StdClient) DoRequestBS(req []byte,
	customResp any, isSteam bool) (*openai.ChatCompletion, error) {

	opts := []option.RequestOption{}
	if len(req) > 0 {
		opts = append(opts, option.WithRequestBody("application/json", req))
	} else {
		return nil, errors.New("request body empty")
	}
	if customResp != nil {
		opts = append(opts, option.WithResponseBodyInto(customResp))
	}
	if isSteam {
		opts = append(opts, option.WithJSONSet("stream", true))
	}
	emptyParams := openai.ChatCompletionNewParams{}

	return me.OAC.Chat.Completions.New(me.ctx, emptyParams, opts...)
}
func (me *StdClient) DoRequest(req *types.CompApiReq) (*types.CompOpenApiResp, error) {

	//fmt.Println(typekit.PrettyPrint(req))
	jsonBytes, err := req.ToBytes()
	if err != nil {
		return nil, err
	}
	customResp := types.CompOpenApiResp{}
	if _, err = me.DoRequestBS(jsonBytes, &customResp, req.Stream); err != nil {
		return nil, err
	}

	if customResp.FgtErrCode != nil && customResp.FgtErrStatusTxt != nil { //针对fastgpt出错但New()不返回错误的情况
		return nil, fmt.Errorf("%s(%d)", *customResp.FgtErrStatusTxt, *customResp.FgtErrCode)
	}
	return &customResp, nil
}

func (me *StdClient) DoRequestStream(req *types.CompApiReq) (*types.CompOpenApiResp, error) {
	var (
		//raw []byte
		raw       *http.Response
		jsonBytes []byte
		err       error
	)

	jsonBytes, err = req.ToBytes()
	if err != nil {
		return nil, err
	}
	if _, err = me.DoRequestBS(jsonBytes, &raw, req.Stream); err != nil {
		return nil, err
	}
	streamOut(me.ctx, raw)

	return nil, nil
}

func (me *StdClient) BuildRequest(req *types.CompApiReq) error {
	return nil
}
