package headmaster

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

	"git.lxtend.com/qqbot/handler"
	"git.lxtend.com/qqbot/model"
	"git.lxtend.com/qqbot/util"
	"github.com/sashabaranov/go-openai"
)

var (
	histories      = make(map[string][]openai.ChatCompletionMessage)
	histories_time = make(map[string]time.Time)
)

func init() {
	handler.RegisterHandler("校长", headmasterHandler)
	handler.RegisterPrivateHandler(headmasterHandler)
}

func headmasterHandler(msg model.Message) (reply model.Reply) {
	from := util.From(msg.GroupInfo.GroupId, msg.UserId)
	if len(msg.RawMsg) > 7 && msg.RawMsg[0:7] == "校长 " {
		return model.Reply{
			ReplyMsg:       ask(from, msg.RawMsg[7:]),
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	// nickname := msg.UserNickName
	return model.Reply{
		ReplyMsg:       ask(from, msg.RawMsg),
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func ask(from string, question string) (reply string) {
	client := openai.NewClientWithConfig(openai.DefaultAzureConfig("none", "http://127.0.0.1:8000/v1"))
	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model:    "minimind",
			Messages: GenRequestFromUsr(from, question),
			// Messages: []openai.ChatCompletionMessage{
			// 	{
			// 		Role:    openai.ChatMessageRoleUser,
			// 		Content: question,
			// 	},
			// },
		},
	)

	if err != nil {
		fmt.Printf("ChatCompletion error: %v\n", err)
		return
	}
	AppendReplyToHistory(from, resp.Choices[0].Message.Content)
	return enterFormatter(resp.Choices[0].Message.Content)
}

func enterFormatter(msgIn string) string {
	return strings.ReplaceAll(msgIn, "\\n", "\n")
}

func GenRequestFromUsr(from string, question string) []openai.ChatCompletionMessage {
	if _, ok := histories[from]; !ok || histories_time[from].Add(2*time.Minute).Before(time.Now()) {
		histories[from] = make([]openai.ChatCompletionMessage, 0)
	}
	histories[from] = append(histories[from], openai.ChatCompletionMessage{
		Role:    openai.ChatMessageRoleUser,
		Content: question,
	})
	return histories[from]
}

func AppendReplyToHistory(from string, reply string) {
	histories[from] = append(histories[from], openai.ChatCompletionMessage{
		Role:    openai.ChatMessageRoleAssistant,
		Content: reply,
	})
	histories_time[from] = time.Now()
	for len(histories[from]) > 10 {
		histories[from] = histories[from][1:]
	}
}
