package main

import (
	"context"
	"encoding/json"
	"log"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"

	"github.com/suno-ai/glockenspiel/studio_canary/apipinger"
)

const (
	baseURL = "https://studio-api.prod.suno.com"
	// interval = 1 * time.Minute
	interval = 2 * time.Second
)

type Config struct {
	Pingers []struct {
		APIURL     string `json:"api_url"`
		Method     string `json:"method"`
		Payload    string `json:"payload,omitempty"` // Optional payload field
		ReturnCode int    `json:"return_code"`
	} `json:"pingers"`
}

func main() {

	// Read the configuration file
	configFile, err := os.Open("config.json")
	if err != nil {
		log.Fatal("Error opening config file:", err)
	}
	defer configFile.Close()

	var config Config
	if err := json.NewDecoder(configFile).Decode(&config); err != nil {
		log.Fatal("Error decoding config file:", err)
	}

	// Create a slice of APIPinger instances based on the config
	var pingers []*apipinger.APIPinger
	for _, p := range config.Pingers {
		pingers = append(pingers, &apipinger.APIPinger{APIURL: baseURL + p.APIURL, Method: p.Method, Payload: p.Payload, ReturnCode: p.ReturnCode})
	}

	ticker := time.NewTicker(interval)
	defer ticker.Stop()

	results := make(chan string)
	var wg sync.WaitGroup

	ctx, cancel := context.WithCancel(context.Background())

	// Handle graceful shutdown
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		<-sigs
		log.Println("Received shutdown signal")
		cancel()
		ticker.Stop()
	}()

	log.Println("Starting canary app to ping API every minute...")

	go func() {
		for result := range results {
			log.Println(result)
		}
	}()

	// Read the Bearer token from an environment variable
	token := os.Getenv("BEARER_TOKEN")
	if token == "" {
		log.Fatal("BEARER_TOKEN environment variable is not set")
	}

	currentPingerIndex := 0

	for {
		select {
		case <-ticker.C:
			if len(pingers) > 0 {
				wg.Add(1)
				go pingers[currentPingerIndex].Ping(ctx, &wg, results, token)
				currentPingerIndex = (currentPingerIndex + 1) % len(pingers)
			}
		case <-ctx.Done():
			wg.Wait()
			close(results)
			log.Println("Shutting down gracefully")
			return
		}
	}
}
