package main

import (
	"bytes"
	"fmt"
	"log"
	"poc-daily-report/pkg/db"
	"poc-daily-report/pkg/feishu"
	"poc-daily-report/pkg/model"
	"sort"
	"text/template"
	"time"

	"github.com/spf13/viper"
)

func main() {
	viper.Set("scope", "prod")
	viper.SetConfigName("conf")     // name of config file (without extension)
	viper.SetConfigType("yaml")     // REQUIRED if the config file does not have the extension in the name
	viper.AddConfigPath("./config") // optionally look for config in the working directory
	viper.SetDefault("template-dir", "./templates/")
	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error config file: %w \n", err))
	}
	regions := []string{"NA", "CO", "APAC", "EMEA", "Japan"}
	regionColor := map[string]string{"NA": "purple", "CO": "orange", "APAC": "carmine", "EMEA": "turquoise", "Japan": "violet"}

	t, err := template.ParseFiles(viper.GetString("template-dir") + "message.template")
	if err != nil {
		log.Fatal(err)
	}
	date := time.Now().Add(-time.Hour * 24)
	focusedClusters, err := db.GetFocusedClusters(date)
	tenantOverviews := generateTemplateStruct(focusedClusters)
	for _, region := range regions {
		regionOverviews := make([]*model.Overview, 0)
		for _, overview := range tenantOverviews {
			fmt.Println(overview.Name, ":", overview.Total)
			if overview.Region == region {
				regionOverviews = append(regionOverviews, overview)
			}
		}
		fmt.Println(region, ":", len(regionOverviews))
		templateData := &model.MessageTemplateData{TenantOverviews: regionOverviews, DocURL: viper.GetString("doc_url")}
		if templateDataFilter(templateData) {
			var bufWriter bytes.Buffer
			t.Execute(&bufWriter, templateData)
			sendCardToPOCReportChat(model.FeishuCardParams{Title: date.Format("2006-01-02") + " " + region + " POC Daily Status Tracking", Color: regionColor[region], Text: bufWriter.String()})
		}
	}
	// update table
	feishu.AppendRecordToTable(focusedClusters, model.FeishuTableParams{AppToken: viper.GetString("feishu_tables.poc_daily_table.app_token"), TableId: viper.GetString("feishu_tables.poc_daily_table.table_id")}, date)
}

func sendCardToDevTierChat(params model.FeishuCardParams) {
	feishu.SendCardToChat(params, viper.GetString("feishu_chats.devtier_chat"))
}

func sendCardToPOCReportChat(params model.FeishuCardParams) {
	feishu.SendCardToChat(params, viper.GetString("feishu_chats.poc_report_chat"))
}

func generateTemplateStruct(focusedClusters []model.FocusedCluster) []*model.Overview {
	tempMap := make(map[string]*model.Overview)
	retOverviews := make([]*model.Overview, 0)
	for _, focusedCluster := range focusedClusters {
		overviewPointer, ok := tempMap[focusedCluster.TenantName]
		if ok {
			overviewPointer.Clusters = append(overviewPointer.Clusters,
				&model.ClusterOverview{ClusterId: focusedCluster.ClusterId,
					MaxQPS:              focusedCluster.MaxQPS,
					QPSOver500Min:       int(focusedCluster.QpsGt500Min),
					Status:              focusedCluster.ClusterStatus.String,
					IsIdle:              24.0-focusedCluster.PausedHour-float64(focusedCluster.QpsGt500Min)/60 > 20,
					NeedPrintPausedHour: (focusedCluster.PausedHour > 0 && focusedCluster.PausedHour < 12),
					PausedHour:          focusedCluster.PausedHour,
				})
			overviewPointer.CalculateClusterCountsAndIsIdle()
		} else {
			newOverviewPointer := &model.Overview{Name: focusedCluster.TenantName,
				TenantId: focusedCluster.TenantId,
				Region:   focusedCluster.Region,
				PlanType: focusedCluster.PlanType,
				IsPOC:    focusedCluster.PlanType == "poc"}
			if focusedCluster.ClusterId != 0 {
				newOverviewPointer.Clusters = append(newOverviewPointer.Clusters,
					&model.ClusterOverview{ClusterId: focusedCluster.ClusterId,
						MaxQPS:              focusedCluster.MaxQPS,
						QPSOver500Min:       int(focusedCluster.QpsGt500Min),
						Status:              focusedCluster.ClusterStatus.String,
						IsIdle:              24-focusedCluster.PausedHour-float64(focusedCluster.QpsGt500Min)/60 > 20,
						NeedPrintPausedHour: (focusedCluster.PausedHour > 0 && focusedCluster.PausedHour < 12),
						PausedHour:          focusedCluster.PausedHour,
					})
			}
			newOverviewPointer.CalculateClusterCountsAndIsIdle()
			retOverviews = append(retOverviews, newOverviewPointer)
			tempMap[newOverviewPointer.Name] = newOverviewPointer
		}
	}
	sort.Sort(model.ByClusterPrior(retOverviews))
	return retOverviews
}

func templateDataFilter(tData *model.MessageTemplateData) bool {
	for _, overview := range tData.TenantOverviews {
		if overview.Total != 0 {
			return true
		}
	}
	return false
}
