package cmd

import (
	"context"
	"fmt"
	"log/slog"
	"os"
	"os/signal"
	"syscall"

	"github.com/spf13/cobra"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/logz"
)

func Run(command *cobra.Command) {
	command.Version = fmt.Sprintf("%s, git ref: %s", Version, GitRef)
	err := run(command)
	// Normally error is logged in the command itself using a proper logger.
	// This error is coming from Cobra itself e.g. incorrect command line flags passed.
	LogAndExitOnError(nil, err)
}

func run(command *cobra.Command) error {
	ctx, cancelFunc := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer cancelFunc()

	return command.ExecuteContext(ctx)
}

func LogAndExitOnError(log *slog.Logger, err error) {
	if err == nil {
		return
	}
	if log == nil {
		log = slog.New(slog.NewJSONHandler(os.Stderr, nil))
	}
	log.Error("Program aborted", logz.Error(err))
	os.Exit(1)
}
