package stations

import (
	"context"
	"fmt"
	"log"
	"time"

	media_utils "github.com/suno-ai/glockenspiel/studio_api_flute/internal/media"
	redis_client "github.com/suno-ai/glockenspiel/studio_api_flute/internal/redis"
)

// StartStreamingForever starts streaming songs forever
func StartStreamingForever(ctx context.Context) {
	songListKey := "suno_stream:song_list"

	streamEvents := "suno_stream:events"

	streamList, err := redis_client.FetchRedisList(songListKey)
	if err != nil {
		log.Printf("Error fetching redis list: %v", err)
		return
	}

	if len(streamList) == 0 {
		song1 := "https://cdn1.suno.ai/b7dff5bf-ca1c-4889-bb94-06a61ea7480a.mp3"
		song2 := "https://cdn1.suno.ai/e4da68a8-8e48-4c5a-9e11-98410b3cbdd5.mp3"
		redis_client.SaveRedisList(songListKey, []string{song1, song2})
		streamList = []string{song1, song2}
	}

	// Start a goroutine to play the streamList
	go func(ctx context.Context) {
		songIndex := 0

		for {
			select {
			case <-ctx.Done():
				return
			default:
				song := streamList[songIndex]
				curSongDuration, err := media_utils.GetMP3Duration(song)
				if err != nil {
					log.Printf("Error getting mp3 duration: %v, move on to the next song", err)
					streamList, err = redis_client.FetchRedisList(songListKey)
					if err != nil {
						log.Printf("Error fetching redis list: %v", err)
						return
					}
					// Move to the next song, wrap around if at the end
					songIndex = (songIndex + 1) % len(streamList)
					continue
				}

				// Send song title and timestamp back to the WebSocket
				for i := 0; i < int(curSongDuration.Seconds()); i += 3 {
					message := fmt.Sprintf("playing: %s, time_in_sec: %d", song, i)
					if err := redis_client.PublishMessage(streamEvents, message); err != nil {
						log.Printf("Error publishing message: %v", err)
						return
					}
					time.Sleep(3 * time.Second)
				}
				streamList, err = redis_client.FetchRedisList(songListKey)
				if err != nil {
					log.Printf("Error fetching redis list: %v", err)
					return
				}
				// Move to the next song, wrap around if at the end
				songIndex = (songIndex + 1) % len(streamList)
			}
		}
	}(ctx)
}
