package main

import (
	"context"
	"fmt"
	"os"

	"github.com/spf13/cobra"
	"github.com/tidbcloud/devops/pkg/infra/log"
	"github.com/tidbcloud/escalation-base/feishu_messager_v2/pkg/infra/config"
	"github.com/tidbcloud/escalation-base/feishu_messager_v2/pkg/infra/deps"
	_ "gorm.io/gorm"
	"sigs.k8s.io/controller-runtime/pkg/manager/signals"
)

var (
	flagConfig string
	globalCtx  context.Context
	globalDeps *deps.Deps
)

func newRootCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:     "feishu-messager-server",
		Version: "v0.0.0",
		Run:     excute,
	}
	cmd.PersistentFlags().StringVar(&flagConfig, "config", "", "path to read root config")
	cmd.MarkFlagsRequiredTogether("config")

	return cmd
}

func excute(cmd *cobra.Command, args []string) {
	err := run(globalCtx, globalDeps)
	exitIfErr(err, "failed to run")
}

func main() {
	globalCtx = signals.SetupSignalHandler()
	cobra.OnInitialize(func() {
		conf, err := config.InitConfig(flagConfig)
		exitIfErr(err, "failed to init config")
		globalDeps, err = setup(globalCtx, conf)
		exitIfErr(err, "failed to setup")
	})

	cmd := newRootCmd()
	err := cmd.Execute()
	exitIfErr(err, "failed to execute cmd")
}

func exitIfErr(err error, msg string) {
	if err != nil {
		if log.Logger.IsZero() {
			fmt.Fprintln(os.Stderr, err.Error())
		} else {
			log.Logger.Error(err, msg)
		}
		os.Exit(1)
	}
}
