package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"os"
	"syscall"

	"github.com/tech/sendico/fx/ingestor/internal/app"
	"github.com/tech/sendico/fx/ingestor/internal/appversion"
	"github.com/tech/sendico/fx/ingestor/internal/signalctx"
	"github.com/tech/sendico/pkg/discovery"
	lf "github.com/tech/sendico/pkg/mlogger/factory"
	"go.uber.org/zap"
)

var (
	configFile  = flag.String("config.file", app.DefaultConfigPath, "Path to the configuration file.")
	debugFlag   = flag.Bool("debug", false, "Enable debug logging.")
	versionFlag = flag.Bool("version", false, "Show version information.")
)

func main() {
	flag.Parse()

	logger := lf.NewLogger(*debugFlag).Named("fx_ingestor")

	logger = logger.With(zap.String("instance_id", discovery.InstanceID()))
	defer logger.Sync() //nolint:errcheck

	appVersion := appversion.Create()
	if *versionFlag {
		if _, err := fmt.Fprintln(os.Stdout, appVersion.Print()); err != nil {
			return
		}

		return
	}

	logger.Info("Starting "+appVersion.Program(), zap.String("version", appVersion.Info()))

	ctx, cancel := signalctx.WithSignals(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer cancel()

	application, err := app.New(logger, *configFile)
	if err != nil {
		logger.Error("Failed to initialise application", zap.Error(err))
	} else {
		if err := application.Run(ctx); err != nil {
			if errors.Is(err, context.Canceled) {
				logger.Info("FX ingestor stopped")

				return
			}

			logger.Error("Ingestor terminated with error", zap.Error(err))
		}
	}

	logger.Info("FX ingestor stopped")
}
