package main

import (
	"dataapps/commons/config"
	"dataapps/commons/httpclient"
	dto "dataapps/internal/dto/sqleditor"
	service "dataapps/internal/service/sqleditor"
	"flag"
	"fmt"
	"strconv"

	_ "github.com/go-sql-driver/mysql"
	"github.com/pingcap/log"
	"github.com/pingcap/tidb/parser"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
	"golang.org/x/net/context"
)

const (
	defaultConfigPath = "/etc/dbaas/config.yaml"
)

func testGetStmtType() {
	sql := "select rank from `sample_data`.`github_events`;"
	stmtType, err := parser.New().ParseOneStmt(sql, "", "")
	if err != nil {
		log.Info("err is " + err.Error())
	}
	log.Info("sql is " + sql + " stmtType is " + stmtType.Text())

}
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))
	}

	testGetStmtType()

	projectId := 43563
	clusterId := 150210
	database := "sample_data"
	question := "how many records in github_events"
	appname := "chat2query-vjXNgCzQ"
	apiKey := "ezg9iyzOe2mx5d1Mz0sklmhiuLglr5DyAbl5GtA7vra87segvCsfzClLq9wn8NnP2"

	localhost := "http://127.0.0.1:8081"
	ctx := context.Background()
	chat2QueryParam := dto.Chat2QueryParam{
		ProjectID:   uint64(projectId),
		ClusterID:   uint64(clusterId),
		Database:    database,
		Instruction: question,
		Apikey:      apiKey,
	}
	res, err := service.ChatBotWithParam(ctx, "chat2chart", &chat2QueryParam)
	tilog.Info(ctx, "service chat2data gen sql", zap.Any("res", res), zap.Any("err", err))
	if err != nil {
		tilog.Info(ctx, "service chat2data gen sql failed"+err.Error())
		return
	}
	testChat2Chart(localhost, apiKey, appname, clusterId)
}

func testChat2Chart(localhost string, apiKey string, appname string, clusterId int) {
	header := map[string]string{"api-key": apiKey}
	url := localhost + "/api/v1beta/apps/" + appname + "/v1/chat2chart"
	params := map[string]string{
		"instruction": "how many  records in github_events",
		"database":    "sample_data",
		"cluster_id":  strconv.Itoa(clusterId),
	}
	resp, code, err := httpclient.GetWithHeader(url, &params, &header)
	if err != nil {
		log.Error("fail to get response ", zap.Error(err))
	}
	log.Info("resp code is  " + strconv.Itoa(code) + " body is " + resp)
}
