package main

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"message-service/commons/config"
	"message-service/commons/database"
	controller "message-service/internal/controller/api"

	"github.com/pingcap/log"
	"github.com/tidbcloud/message-service/idl/pbgen/proto/api"
)

const (
	host              = "http://127.0.0.1:10010"
	defaultConfigPath = "/etc/dbaas/config.yaml"
)

func testChat2Chart(req *api.ChatBotReq) {
	ctx := context.Background()
	service := controller.NewChatBotService()
	resp, err := service.ChatBot(ctx, req)
	if err != nil {
		log.Error("chatBot failed. " + err.Error())
	}
	respObj := Chat2ChartResp{}
	json.Unmarshal([]byte(resp.Completion), &respObj)
	log.Info(fmt.Sprintf("%+v", respObj))
}

func connectDB() {
	ctx := context.Background()
	conf := config.Global()
	// Connect database
	database.Connect(ctx,
		conf.MysqlConf.User,
		conf.MysqlConf.Password,
		conf.MysqlConf.Host,
		conf.MysqlConf.Port,
		conf.MysqlConf.Database,
		conf.MysqlConf.CharSet,
		conf.MysqlConf.TimeZone,
	)

}

type Chat2QueryAuthInfo struct {
	ApiKey    string `json:"api_key"`
	AppID     string `json:"app_id"`
	OrgID     uint64 `json:"org_id"`
	ProjectID uint64 `json:"project_id"`
}

type ChartInfo struct {
	ChartName string                 `json:"chartName"`
	Title     string                 `json:"title"`
	Options   map[string]interface{} `json:"options"`
}

type Chat2ChartResp struct {
	Sql       string    `json:"sql"`
	ChartInfo ChartInfo `json:"chart"`
	Questions []string  `json:"questions"`
}

func main() {
	var configPath string
	flag.StringVar(&configPath, "config-path", defaultConfigPath, "DBaaS configuration file path")
	flag.Parse()
	err := config.InitConfig(configPath)
	if err != nil {
		panic(fmt.Sprintf("Initialize configuration failed, err: %+v", err))
	}
	connectDB()
	req := &api.ChatBotReq{
		BotType:   "chat2chart",
		ProjectId: 43563,
		ClusterId: 150210,
		Database:  "sample_data",
		Question:  "top 10 companies in 2021",
		Caller:    "bing.wang@pingcap.com",
	}
	testChat2Chart(req)
}
