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"
	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")
	defer logger.Sync()

	av := appversion.Create()
	if *versionFlag {
		fmt.Fprintln(os.Stdout, av.Print())
		return
	}

	logger.Info(fmt.Sprintf("Starting %s", av.Program()), zap.String("version", av.Info()))

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

	application, err := app.New(logger, *configFile)
	if err != nil {
		logger.Fatal("Failed to initialise application", zap.Error(err))
	}

	if err := application.Run(ctx); err != nil {
		if errors.Is(err, context.Canceled) {
			logger.Info("FX ingestor stopped")
			return
		}
		logger.Fatal("Ingestor terminated with error", zap.Error(err))
	}

	logger.Info("FX ingestor stopped")
}
