package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"git.threefold.info/herocode/heroagent/pkg/servers/heroagent"
)

func main() {
	log.Println("Starting job management test...")

	// Create a configuration for the server factory
	config := heroagent.DefaultConfig()

	// Customize configuration if needed
	config.Redis.TCPPort = 6379
	config.Redis.UnixSocketPath = "" // Use TCP connection only
	config.Jobs.OurDBPath = "/tmp/jobsdb"
	config.Jobs.WorkerCount = 3
	config.Jobs.QueuePollInterval = 200 * time.Millisecond

	// Only enable Redis and Jobs for this test
	config.EnableRedis = true
	config.EnableWebDAV = false
	config.EnableUI = false
	config.EnableJobs = true

	// Create server factory
	factory := heroagent.New(config)

	// Start servers
	if err := factory.Start(); err != nil {
		log.Fatalf("Failed to start servers: %v", err)
	}

	// Get job manager
	jobManager := factory.GetJobManager()
	if jobManager == nil {
		log.Fatalf("Job manager not initialized")
	}

	// Create some test jobs
	createTestJobs(jobManager)

	// Wait for interrupt signal
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
	<-sigCh

	// Stop servers
	if err := factory.Stop(); err != nil {
		log.Fatalf("Failed to stop servers: %v", err)
	}

	log.Println("Job management test completed")
}

func createTestJobs(jobManager *heroagent.JobManager) {
	// Create a few test jobs with different topics
	topics := []string{"email", "notification", "report"}

	for i := 0; i < 5; i++ {
		for _, topic := range topics {
			// Create job
			params := fmt.Sprintf(`{"action": "process", "data": "test data %d for %s"}`, i, topic)
			job, err := jobManager.CreateJob(topic, params)
			if err != nil {
				log.Printf("Failed to create job: %v", err)
				continue
			}

			log.Printf("Created job %d with topic %s", job.JobID, job.Topic)
		}

		// Sleep briefly between batches
		time.Sleep(500 * time.Millisecond)
	}
}
