Imports System.Diagnostics
Imports System.Environment
Imports System.IO
Imports System.Reflection

Module FFMPEG_Wrapper_Module

    Sub Main(ByVal args() As String)
        ' 1. Lizenzhinweis (Wichtig für die GPL-Konformität)
        Console.WriteLine("FFMPEG_Wrapper: Dieses Programm dient als Bridge für FFmpeg (GPL).")
        If args.Length = 0 Then
            Console.Error.WriteLine("FEHLER: Keine Kommandozeilen-Argumente übergeben. Erwarte FFmpeg-Befehlsstring.")
            ExitCode = 1 ' Fehlercode setzen
            Exit Sub
        End If
        Dim quotedArgs As New List(Of String)()
        For Each arg In args
            If Not arg.StartsWith("""") AndAlso arg.Contains(" ") AndAlso (arg.Contains(":") OrElse arg.Contains("\")) Then
                quotedArgs.Add($"""{arg}""")
            Else
                quotedArgs.Add(arg)
            End If
        Next
        Dim ffmpegArgs As String = String.Join(" ", quotedArgs)
        Dim wrapperDir As String = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
        Dim ffmpegExePath As String = Path.Combine(wrapperDir, "ffmpeg.exe")
        If Not File.Exists(ffmpegExePath) Then
            Console.Error.WriteLine($"FEHLER: Die Datei '{ffmpegExePath}' wurde nicht gefunden. Erwartet in: {wrapperDir}")
            ExitCode = 2
            Exit Sub
        End If
        Dim startInfo As New ProcessStartInfo With {
            .FileName = ffmpegExePath,
            .Arguments = ffmpegArgs,
            .WorkingDirectory = wrapperDir,
            .UseShellExecute = False,
            .RedirectStandardOutput = True,
            .RedirectStandardError = True,
            .CreateNoWindow = True
        }

        Using ffmpegProcess As New Process With {.StartInfo = startInfo}
            AddHandler ffmpegProcess.OutputDataReceived, Sub(sender, e)
                                                             If e.Data IsNot Nothing Then Console.WriteLine(e.Data)
                                                         End Sub

            AddHandler ffmpegProcess.ErrorDataReceived, Sub(sender, e)
                                                            If e.Data IsNot Nothing Then Console.Error.WriteLine(e.Data)
                                                        End Sub

            Try
                ffmpegProcess.Start()
                ffmpegProcess.BeginOutputReadLine()
                ffmpegProcess.BeginErrorReadLine()

                ffmpegProcess.WaitForExit()

                ExitCode = ffmpegProcess.ExitCode

            Catch ex As Exception
                Console.Error.WriteLine($"FEHLER beim Starten von FFmpeg: {ex.Message}")
                ExitCode = 3
            End Try
        End Using
    End Sub

End Module
