package main

import (
	"context"
	"database/sql"
	"dataservices/commons/apikeygenerator"
	"dataservices/commons/eventbus"
	"dataservices/ddb"
	"flag"
	"fmt"
	"log"
	"net"

	"dataservices/commons/config"
	"dataservices/commons/database"
	"dataservices/commons/logger"
	"dataservices/commons/metrics"
	"dataservices/commons/sentry"
	"dataservices/commons/sessioncache"
	"dataservices/dbhubsdk"
	dataapi_controller "dataservices/internal/controller/dataapi"

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/tidbcloud/dataservices/idl/pbgen/proto/dataapi"

	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
	"github.com/tidbcloud/pkgv2/version"
	"github.com/tidbcloud/tiinf/errs"
	"github.com/tidbcloud/tiinf/monitor/tilog"
	"github.com/tidbcloud/tiinf/monitor/titracing"
	"github.com/tidbcloud/tiinf/transport/http/tigin"
	tigrpc "github.com/tidbcloud/tiinf/transport/tigrpc/server"
	"go.uber.org/zap"
	"google.golang.org/grpc"
)

const (
	componentName     = "dataservices-dataapi"
	defaultConfigPath = "/etc/dbaas/config.yaml"
	cacheSessionNum   = 256
)

func main() {
	var configPath string
	flag.StringVar(&configPath, "config-path", defaultConfigPath, "DBaaS configuration file path")
	flag.Parse()
	ctx := context.Background()

	config.InitConfig(configPath)

	err := sentry.SetupLoggerAndSentry(config.Global().SentryConf.DSN, config.Global().SentryConf.Environment, config.Global().SentryConf.LogLevel)
	if err != nil {
		panic(fmt.Sprintf("Initialize logger and sentry failed: %+v", err))
	}
	tilog.Info(context.Background(), fmt.Sprintf("Starting %s service", componentName),
		zap.String("gitHash", version.GitHash),
		zap.String("logLevel", config.Global().ServerConf.LogLevel))

	config := config.Global()
	tilog.Info(context.Background(), "service config", logger.Redact("config", config), zap.String("env", config.CurrentEnv()))
	sqlDB := database.Connect(ctx,
		config.MysqlConf.User,
		config.MysqlConf.Password,
		config.MysqlConf.Host,
		config.MysqlConf.Port,
		config.MysqlConf.Database,
		config.MysqlConf.CharSet,
		config.MysqlConf.TimeZone,
	)

	eventbusStartup(ctx, sqlDB)

	apikeygenerator.InitEncrypter(
		config.DataApiKeyConf.SecretKey,
		config.DataApiKeyConf.SecretIv,
	)

	metrics.RegisterDataApiMetrics()
	dbhubsdk.InitSdk(
		config.DBHubSdkConf.KubeConfigPath,
		config.DBHubSdkConf.GardenerProjectName,
		config.DBHubSdkConf.InfraAPIConfigPath)

	sessioncache.Init(cacheSessionNum)

	if err := ddb.Init(ctx, config); err != nil {
		log.Fatal("Initialize dynamodb client failed", zap.Error(err))
	}

	startup()
}

func startup() {
	go startupTracing()
	go startupMetrics()
	startupGRPC()
}

func startupTracing() {
	// jaeger
	if _, err := titracing.InitJaeger(componentName); err != nil {
		panic(fmt.Sprintf("failed to init tracing, err=%v", err))
	}
}

func startupGRPC() {
	grpcServer := newGRPCServer()
	registerGRPCServices(grpcServer)
	tilog.Info(context.Background(), "register grpc services, port is "+string(config.Global().ServerConf.GrpcPort))
	listen, err := net.Listen("tcp", ":"+config.Global().ServerConf.GrpcPort)
	if err != nil {
		panic(err)
	}
	err = grpcServer.Serve(listen)
	if err != nil {
		panic(err)
	}
}

func startupMetrics() {
	/* metrics */
	mEng := tigin.Default()
	mEng.Any("/metrics", prometheusHandler())
	mEng.Run("0.0.0.0:" + config.Global().ServerConf.MetricsPort)
}

func prometheusHandler() gin.HandlerFunc {
	h := promhttp.Handler()

	return func(c *gin.Context) {
		h.ServeHTTP(c.Writer, c.Request)
	}
}

func newGRPCServer() *grpc.Server {
	server := tigrpc.NewServer(
		tigrpc.WithDefault(),
		tigrpc.WithUnaryInterceptors(
			grpc_middleware.ChainUnaryServer(
				metrics.UnaryServerInterceptor(),
				errs.UnaryServerInterceptor(),
			),
		),
	)
	return server
}

func registerGRPCServices(s *grpc.Server) {
	dataapi.RegisterDataAPIServiceServer(s, dataapi_controller.NewDataAPIServiceService())
}

func eventbusStartup(ctx context.Context, db *sql.DB) {
	if config.IsLocalMode() {
		return
	}
	bus := eventbus.Init("dataservice_dataapi", db)
	if err := bus.Run(); err != nil {
		tilog.Fatal(ctx, "Eventbus run failed", zap.Error(err))
	}
}
