package main

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

	"aigateway.local/core/internal/platform/config"
	"aigateway.local/core/internal/platform/cryptox"
	"aigateway.local/core/internal/platform/database"
	platformid "aigateway.local/core/internal/platform/id"
	"aigateway.local/core/internal/scheduler"
)

func main() {
	logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
	cfg, err := config.Load()
	if err != nil {
		logger.Error("invalid configuration", "error", err)
		os.Exit(1)
	}
	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()
	db, err := database.Open(ctx, cfg.Database)
	if err != nil {
		logger.Error("database initialization failed", "error", err)
		os.Exit(1)
	}
	defer db.Close()
	cipher, err := cryptox.NewKeyring(cfg.Credentials.MasterKey, cfg.Credentials.KEKVersion, cfg.Credentials.KEKKeyring, "scheduled-task-api-key")
	if err != nil {
		logger.Error("scheduled task cipher initialization failed", "error", err)
		os.Exit(1)
	}
	workerID, err := platformid.NewUUID()
	if err != nil {
		logger.Error("worker ID generation failed", "error", err)
		os.Exit(1)
	}
	service := scheduler.NewService(db, cipher)
	engine := scheduler.NewEngine(service, cfg.Scheduler.GatewayBaseURL, "scheduler-"+workerID, cfg.Scheduler.BatchSize, cfg.Scheduler.MaxAttempts, cfg.Scheduler.ExecutionTimeout, logger)
	ticker := time.NewTicker(cfg.Scheduler.PollInterval)
	defer ticker.Stop()
	logger.Info("scheduler worker started", "worker_id", workerID, "poll_interval", cfg.Scheduler.PollInterval)
	for {
		processed, tickErr := engine.Tick(ctx, time.Now())
		if tickErr != nil && ctx.Err() == nil {
			logger.Error("scheduler tick failed", "error", tickErr)
		} else if processed > 0 {
			logger.Info("scheduler batch complete", "processed", processed)
		}
		select {
		case <-ctx.Done():
			logger.Info("scheduler worker stopped")
			return
		case <-ticker.C:
		}
	}
}
