package main

import (
	"flag"

	"github.com/gin-contrib/pprof"
	"go.uber.org/zap"

	"github.com/pingcap-inc/chaosAPI/pkg/api"
	"github.com/pingcap-inc/chaosAPI/pkg/infra"

	"github.com/gin-gonic/gin"
	error2 "github.com/pingcap-inc/clinic/pkg/api/error"
	"github.com/pingcap/log"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"

	_ "github.com/pingcap-inc/chaosAPI/docs"
)

var (
	cfgPath       string
	secretCfgPath string
)

// @title Chaos API
// @version 1.0
// @description This is a server of API to inject fault into tidb cluster.

// @BasePath  /
func main() {
	flag.StringVar(&cfgPath, "c", "", "chaos_api -c=/path/to/config.yaml")
	flag.StringVar(&secretCfgPath, "s", "", "chaos_api -c=/path/to/secret-config.yaml")
	flag.Parse()
	if cfgPath == "" {
		log.Fatal("config path is empty, please use -c to specify the config path")
	}

	config, err := infra.NewConfig(cfgPath, secretCfgPath)
	if err != nil {
		log.Fatal("init config failed", zap.Error(err))
	}

	client := infra.Setup(*config)

	route := gin.New()
	route.Use(gin.Recovery())
	route.Use(error2.ErrorHandlerFn())
	pprof.Register(route)
	route.GET("/chaos/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	service := api.NewService(client)
	api.RegisterRoute(route, service)

	err = route.Run(config.ServerConfig.Addr)
	if err != nil {
		log.Fatal("can not start server", zap.Error(err))
	}
}
