package main

import (
	"context"
	"fmt"
	"log"
	"flag"

	"github.com/PullRequestInc/go-gpt3"
	"samhofi.us/x/keybase/v2"
	"samhofi.us/x/keybase/v2/types/chat1"
)



var (
	k = keybase.NewKeybase()
	client gpt3.Client
	api_key string
)

func init() {
	flag.StringVar(&api_key, "k", "", "API Key for GPT-3 Client")
}

func logError(e error) {
	log.Printf("KEYBASE: %+v", e)
}

func routeMessage(m chat1.MsgSummary) {
	if k.Username == m.Sender.Username {
		return
	}

	log.Printf("\nIncoming message:\n\n%+v\n-----", m)

	if m.Content.TypeName != "text" {
		return
	}
	history, err := k.ReadConversation(m.ConvID)
	if err != nil {
		logError(err)
		return
	}
	prompt := fmt.Sprintf("The following is a conversation with Alan Turing (%+v). %+v is helpful, creative, clever, and very friendly.\n\n", k.Username, k.Username)
	convo := history.Messages[:20]
	for len(convo) > 0 {
		msg := convo[len(convo)-1]
		convo = convo[:len(convo)-1]
		if msg.Msg.Content.TypeName != "text" {
			continue
		}
		prompt += msg.Msg.Sender.Username + ": " + msg.Msg.Content.Text.Body + "\n"
	}
	prompt += fmt.Sprintf("%+v: ", k.Username)
	log.Printf("\nPrompt: %+v\n-----", prompt)
	resp, err := client.Completion(context.Background(), gpt3.CompletionRequest{
		Prompt: []string{prompt},
		MaxTokens: gpt3.IntPtr(256),
		Stop: []string{"\n"},
		Temperature: gpt3.Float32Ptr(0.9),
		TopP: gpt3.Float32Ptr(1),
		FrequencyPenalty: 0,
		PresencePenalty: 0.6,
		
	})
	if err != nil {
		logError(err)
		k.ReactByConvID(m.ConvID, m.Id, ":-1:")
		return
	}

	log.Printf("\nResponses to message:\n\n%+v\n-----", resp)
	k.SendMessageByConvID(m.ConvID, resp.Choices[0].Text)
	
}


func main() {
	client = gpt3.NewClient(api_key, gpt3.WithDefaultEngine("ada"))
	err := logError
	chat := routeMessage
	handlers := keybase.Handlers{
		ChatHandler: &chat,
		ErrorHandler: &err,
	}
	k.Run(handlers, &keybase.RunOptions{})
}