// Package http add by blacknc <blacknc@163.com> at 2023/04/03 15:46:39
package http

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/tidbcloud/tiinf/errs"
)

func ChatBot(ctx context.Context, orgID, projectID uint64, req *ChatBotReq) (resp *ChatBotResp, e error) {
	url := fmt.Sprintf("/inner/aipower/api/v1/orgs/%d/projects/%d/bot", orgID, projectID)
	resp = &ChatBotResp{}
	e = postToAiPower(ctx, url, req, resp, time.Duration(req.Timeout)*time.Millisecond)
	return
}

func postToAiPower(ctx context.Context, url string, req interface{}, resp interface{}, timeout time.Duration) (err error) {
	defer func() {
		recordHttpCounterMetric("aipower", err)
	}()
	err = postRequestToGlobal(ctx, "aipower", url, req, resp, WithTimeout(timeout))
	if tierr, ok := errs.AsTiError(err); ok {
		if tierr.Cause() != nil && strings.Contains(tierr.Cause().Error(), "context deadline") {
			return errs.NewInternalServerError(err.Error()+", "+tierr.Cause().Error(), nil)
		}
	}
	return err
}

type ChatBotReq struct {
	SessionID             string   `json:"session_id"`
	Question              string   `json:"question"` // 提问
	BotType               string   `json:"bot_type"` // chat2sql/chat2chart...
	ClusterID             uint64   `json:"cluster_id,string"`
	Database              string   `json:"database"`                // 针对的数据库
	PromptTemplate        string   `json:"prompt_template"`         // 使用自定义模板（一般不传）
	PromptTemplateVersion string   `json:"prompt_template_version"` // 使用自定义模板（一般不传）
	Tables                []string `json:"tables"`                  // 限定哪些表
	Model                 string   `json:"model"`                   // openai model, gpt-3.5-turbo...
	Caller                string   `json:"caller"`                  // 调用者email
	Timeout               int      `json:"timeout"`                 // 超时时间，单位毫秒
	OrgID                 uint64   `json:"org_id,string"`
	AppID                 uint64   `json:"app_id"`
	AppKey                string   `json:"app_key"`
	Endpoint              string   `json:"endpoint"`
	Source                string   `json:"source"`
}

type ChatBotResp struct {
	Code          int    `json:"code"`
	Message       string `json:"message"`
	SessionId     string `json:"session_id"`
	Prompt        string `json:"prompt"`
	Response      string `json:"response"`
	TokenUsed     int32  `json:"token_used"`
	PromptVersion string `json:"prompt_version"`
	Database      string `json:"database"`
	ExecuteTime   int64  `json:"execute_time"`
}

func (r *ChatBotResp) GetErrCode() int {
	return r.Code
}
func (r *ChatBotResp) GetErrMsg() string {
	return r.Message
}

func (r *ChatBotResp) GetCompletion() string {
	return r.Response
}
func (r *ChatBotResp) GetSessionId() string {
	return r.SessionId
}
func (r *ChatBotResp) GetDatabase() string {
	return r.Database
}
func (r *ChatBotResp) GetPrompt() string {
	return r.Prompt
}
func (r *ChatBotResp) GetPromptVersion() string {
	return r.PromptVersion
}
func (r *ChatBotResp) GetTokenUsed() int32 {
	return r.TokenUsed
}
