package transfer

import (
	"context"
	"log"
	"m3u8-downloader/pkg/constants"
	"m3u8-downloader/pkg/transfer"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func RunTransferOnly(eventName string) {
	log.Printf("Starting transfer-only mode for event: %s", eventName)

	// Setup context and signal handling
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-sigChan
		log.Println("Shutting down transfer service...")
		cancel()
	}()

	// Check if NAS transfer is enabled
	if !constants.EnableNASTransfer {
		log.Fatal("NAS transfer is disabled in constants. Please enable it to use transfer-only mode.")
	}

	// Verify local event directory exists
	localEventPath := constants.LocalOutputDirPath + "/" + eventName
	if _, err := os.Stat(localEventPath); os.IsNotExist(err) {
		log.Fatalf("Local event directory does not exist: %s", localEventPath)
	}

	// Create transfer service
	transferService, err := transfer.NewTrasferService(constants.NASOutputPath, eventName)
	if err != nil {
		log.Fatalf("Failed to create transfer service: %v", err)
	}

	// Find and queue existing files
	if err := transferService.QueueExistingFiles(localEventPath); err != nil {
		log.Fatalf("Failed to queue existing files: %v", err)
	}

	// Start transfer service
	log.Println("Starting transfer service...")
	if err := transferService.Start(ctx); err != nil && err != context.Canceled {
		log.Printf("Transfer service error: %v", err)
	}

	// Graceful shutdown
	shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer shutdownCancel()
	transferService.Shutdown(shutdownCtx)

	log.Println("Transfer-only mode completed.")
}
