package main

import (
	"errors"
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/pingcap/log"
	"github.com/tidbcloud/observability/pkg/common/constants"
	"github.com/tidbcloud/observability/pkg/common/utils"
	"github.com/tidbcloud/observability/pkg/regionalapi/apiinterceptor"
	"go.uber.org/zap"
)

func main() {
	utils.InitLog("info")

	g := gin.New()
	g.Use(cors.New(corsConfig()))

	g.GET("/:id/metrics", GetMetrics)

	addr := fmt.Sprintf(":%d", 8484)

	srv := &http.Server{
		Addr:              addr,
		Handler:           g,
		ReadHeaderTimeout: constants.GinReadHeaderTimeout,
	}
	if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
		log.Info("listen error", zap.Error(err))
	}
}

func GetMetrics(c *gin.Context) {
	id := c.Param("id")
	component := hash(id)

	data, err := get(component.MI)
	if err != nil {
		log.Error("get metrics error", zap.Error(err))
		apiinterceptor.Fail(c, err)
	}

	replacedData := component.MI.replace(data, component.Index)
	// convert
	log.Info("metrics data", zap.String("data", replacedData))
	c.String(http.StatusOK, replacedData)
}

func hash(id string) Component {
	i, err := strconv.Atoi(id)
	if err != nil {
		panic(err)
	}

	if i <= 10 {
		return Component{
			Name:  "PD",
			Index: i,
			MI:    PDMetrics{},
		}
	}
	if i > 10 && i <= 100 {
		return Component{
			Name:  "TiDB",
			Index: i,
			MI:    TiDBMetrics{},
		}
	}
	if i > 100 && i <= 500 {
		return Component{
			Name:  "TiKV",
			Index: i,
			MI:    TiKVMetrics{},
		}
	}
	//if i > 500 && i >= 600 {
	//	return Component{
	//		Name:  "TiFlash",
	//		Index: i,
	//		MI:    TiFlashMetrics{},
	//	}
	//}
	panic("id > 600")
}

// corsConfig
// @Description: build cors config
// @return cors.Config
func corsConfig() cors.Config {
	config := cors.DefaultConfig()
	config.AllowHeaders = []string{"*"}
	config.AllowCredentials = true
	config.AllowOriginFunc = func(origin string) bool {
		return true
	}
	return config
}
