package main

import (
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

func transcodeIfNeeded(simDir, filename string) string {
	ext := strings.ToLower(filepath.Ext(filename))
	if ext != ".avi" {
		return filename
	}

	baseName := strings.TrimSuffix(filename, filepath.Ext(filename))
	mp4Filename := baseName + ".mp4"
	aviPath := filepath.Join(simDir, filename)
	mp4Path := filepath.Join(simDir, mp4Filename)

	// If the file was already transcoded prior, just remove the stale .avi and return .mp4
	if _, err := os.Stat(mp4Path); err == nil {
		os.Remove(aviPath)
		return mp4Filename
	}

	log.Printf("Attempting GPU Transcoding (h264_nvenc) %s to %s...\n", aviPath, mp4Path)
	cmdGPU := exec.Command("ffmpeg", "-y", "-i", aviPath, "-c:v", "h264_nvenc", "-pix_fmt", "yuv420p", "-movflags", "+faststart", mp4Path)
	
	if err := cmdGPU.Run(); err == nil {
		os.Remove(aviPath)
		return mp4Filename
	}

	log.Printf("GPU transcoding failed/unavailable, falling back to CPU (libx264) for %s...\n", aviPath)
	cmdCPU := exec.Command("ffmpeg", "-y", "-i", aviPath, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-movflags", "+faststart", mp4Path)
	
	if err := cmdCPU.Run(); err == nil {
		os.Remove(aviPath)
		return mp4Filename
	} else {
		log.Println("Failed to transcode (both GPU and CPU):", err)
		return filename
	}
}
