package main

import (
	"context"
	"database/sql"
	"dataservices/commons/redisutil"
	"dataservices/commons/sentry"
	"dataservices/ddb"
	"flag"
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/tidbcloud/pkgv2/version"

	"dataservices/commons/config"
	"dataservices/commons/database"
	"dataservices/commons/eventbus"
	dslogger "dataservices/commons/logger"
	"dataservices/commons/metrics"

	"dataservices/worker"

	"github.com/tidbcloud/tiinf/monitor/tilog"
	"github.com/tidbcloud/tiinf/monitor/titracing"
	"github.com/tidbcloud/tiinf/transport/http/tigin"
	"go.uber.org/zap"
)

const (
	componentName     = "dataservice-central"
	defaultConfigPath = "/etc/dbaas/config.yaml"
)

// @title DataAPI API
// @version 1.0
// @description This is Data API server

// @host 127.0.0.1:8080
// @BasePath /api/v1/dataservices
func main() {
	var configPath string
	flag.StringVar(&configPath, "config-path", defaultConfigPath, "DBaaS configuration file path")
	flag.Parse()
	ctx := context.Background()
	logger := tilog.WithContextL(ctx).With(zap.String("server", componentName+"-worker"))

	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))
	}
	logger.Info(fmt.Sprintf("Starting %s service", componentName),
		zap.String("gitHash", version.GitHash),
		zap.String("logLevel", config.Global().ServerConf.LogLevel))

	// Load config
	err = config.InitConfig(configPath)
	if err != nil {
		// TODO: unexpected error like this, should we throw a alert/page, just log seems not enough ?
		logger.Fatal("Initialize configuration failed", zap.Error(err))
	}

	setup(ctx)

	// Connect database
	config := config.Global()
	tilog.Info(context.Background(), "service config", dslogger.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)

	metrics.RegisterCentralMetrics()

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

	err = redisutil.NewRedisClient(ctx, config)
	if err != nil {
		tilog.Fatal(ctx, "Initialize redis client failed.", zap.Error(err))
	}

	go startupMetrics()

	// TODO(CaC-biz): a standard cronjob frame.
	workerManager := worker.NewWorkerManager(
		worker.NewDeploymentWorker(ctx),
		worker.NewCommonTaskWorker(ctx),
		worker.NewEtlWorker(ctx),
		worker.NewPrivatelinkTaskWorker(ctx),
	)
	workerManager.Process()

	sigQuit := make(chan os.Signal, 1)
	signal.Notify(sigQuit, syscall.SIGINT, syscall.SIGTERM)
	sig := <-sigQuit
	logger.Info("caught signal, shutting down", zap.String("sig", sig.String()))

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	workerManager.Shutdown(ctx)
	logger.Info("dataservice-central-worker shutdown completed")
}

func setup(ctx context.Context) {
	// jaeger
	if _, err := titracing.InitJaeger(componentName); err != nil {
		tilog.Error(ctx, "init tiinf jaeger provider failed", zap.Error(err))
		panic(fmt.Sprintf("failed to init tracing, err=%v", err))
	}
}

func eventbusStartup(ctx context.Context, db *sql.DB) {
	if config.IsLocalMode() {
		return
	}
	bus := eventbus.Init("dataservice_worker", db)
	if err := bus.Run(); err != nil {
		tilog.Fatal(ctx, "Eventbus run failed", zap.Error(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)
	}
}
