package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/joho/godotenv"
	"github.com/suno-ai/glockenspiel/studio_api_flute/internal/ably"
	"github.com/suno-ai/glockenspiel/studio_api_flute/internal/api"
	"github.com/suno-ai/glockenspiel/studio_api_flute/internal/aws"
	"github.com/suno-ai/glockenspiel/studio_api_flute/internal/stream"
	"github.com/suno-ai/glockenspiel/studio_api_flute/internal/stream/stream_workers/generate_worker"
	"github.com/suno-ai/glockenspiel/studio_api_flute/internal/stream/stream_workers/radio_worker"
)

func main() {

	if os.Getenv("ENV") == "local" {
		err := godotenv.Load()
		if err != nil {
			log.Fatalf("Error loading .env file: %v", err)
		}
	}

	aws.InitS3Client()

	// Initialize the router
	mux := api.SetupRouter()

	// stations.StartStreamingForever(context.Background())

	// Create a context for graceful shutdown
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	go stream.NewStreamServer([]stream.StreamWorker{
		generate_worker.NewGenerateWorker(ably.GetAblyClient(), stream.GenerateChannel),
		radio_worker.NewRadioWorker(ably.GetAblyClient(), stream.RadioChannel),
	}).Start(ctx)

	srv := &http.Server{
		Addr:    ":9090",
		Handler: mux,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	// Handle graceful shutdown
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	<-sigChan
	log.Println("Shutting down server...")

	// Cancel the context to stop the StreamServer
	cancel()

	// Create a deadline to wait for.
	ctxShutDown, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctxShutDown); err != nil {
		log.Fatalf("Server forced to shutdown: %v", err)
	}

	log.Println("Server exiting")
}
