package main

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"message-service/commons/config"
	"message-service/commons/utils"
	"os"
	"strings"

	service "message-service/internal/service/central"
)

const (
	host                    = "http://127.0.0.1:10010"
	defaultConfigPath       = "/etc/dbaas/config.yaml"
	defaulttableSqlPath     = "./table_info.json"
	defaultQuestionFilePath = "./questionFile.list"
	defaultOutputPath       = "./table_info_with_question.json"
)

var exePath, _ = os.Executable()

type TableInfo struct {
	Database  string   `json:"database"`
	Table     string   `json:"table"`
	Sql       string   `json:"sql"`
	ColName   []string `json:"col_names"`
	Questions []string `json:"questions"`
}

func main() {
	var configPath string
	var tableSqlPath string
	var questionFilePath string
	var outputPath string
	flag.StringVar(&configPath, "config-path", defaultConfigPath, "DBaaS configuration file path")
	flag.StringVar(&tableSqlPath, "table-sql", defaulttableSqlPath, "DBaaS configuration file path")
	flag.StringVar(&questionFilePath, "question-file", defaultQuestionFilePath, "DBaaS configuration file path")
	flag.StringVar(&outputPath, "output", defaultOutputPath, "")
	flag.Parse()
	err := config.InitConfig(configPath)
	if err != nil {
		panic(fmt.Sprintf("Initialize configuration failed, err: %+v", err))
	}
	sql, _ := utils.ReadFileToString(tableSqlPath)
	colStr := "id,type,created_at,repo_id,repo_name,actor_id,actor_login,actor_location,language,additions,deletions,action,number,commit_id,comment_id,org_login,org_id,state,closed_at,comments,pr_merged_at,pr_merged,pr_changed_files,pr_review_comments,pr_or_issue_id,event_day,event_month,author_association,event_year,push_size,push_distinct_size"
	tableInfo := TableInfo{
		Database: "gharchive_dev",
		Table:    "github_events",
		Sql:      sql,
		ColName:  strings.Split(colStr, ","),
	}
	questions, err := utils.ReadFileToList(questionFilePath)
	tableInfo.Questions = *questions
	tableInfos := []TableInfo{tableInfo}
	outputStr, err := json.MarshalIndent(tableInfos, "", "\t")
	utils.WriteStringToFile(outputPath, string(outputStr))
}

func GenQuestionsByCompletion(tableInfo string) (string, error) {
	ctx := context.Background()
	prompt := `### MySQL table
` + tableInfo + `
### List 50 interesting questions to ask about the data`
	completion, err := service.CreateCompletionTextDavinci(ctx, prompt)
	if err != nil {
		return "", err
	}
	return completion, nil
}
