package main

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

	"github.com/google/uuid"

	"qycw/go-server/internal/bootstrap"
	"qycw/go-server/internal/config"
	"qycw/go-server/internal/jobs"
	"qycw/go-server/internal/license"
)

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))

	cfg, err := config.LoadBootstrap(os.Args[1:])
	if err != nil {
		logger.Error("load bootstrap config failed", "error", err)
		os.Exit(2)
	}

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	app, err := bootstrap.New(ctx, cfg, logger)
	if err != nil {
		logger.Error("bootstrap failed", "error", err)
		os.Exit(1)
	}
	defer app.Close()
	if app.LicenseManager != nil {
		if err := app.LicenseManager.InitEvaluator(ctx); err != nil {
			logger.Error("license public key unavailable, cannot start worker safely", "error", err)
			os.Exit(1)
		}
	}
	reporter := license.NewReporter(app.LicenseManager, cfg.LicenseHeartbeatInterval, logger)
	if app.Redis != nil {
		reporter = reporter.WithRedis(app.Redis, "worker-"+uuid.NewString())
	}
	go func() {
		if err := reporter.Run(ctx); err != nil {
			logger.Error("authorization reporter stopped", "error", err)
			stop()
		}
	}()

	runner := jobs.NewRunner(app, logger)
	if err := runner.Run(ctx); err != nil {
		logger.Error("worker stopped with error", "error", err)
		os.Exit(1)
	}
}
