using System.Diagnostics;
using VideoStudy.Shared;

namespace VideoStudy.Desktop.Services;

public class FFmpegService
{
    private string _ffmpegPath = "ffmpeg"; // Assume in PATH by default

    public FFmpegService()
    {
        // Simple check if ffmpeg is available?
        // For now, we trust the user or the PATH.
        // In a robust implementation, we would check/download.
    }

    public async Task ExtractAudioForWhisperAsync(string videoPath, string outputPath)
    {
        // Whisper expects 16kHz, Mono, S16LE usually
        var args = $"-y -i \"{videoPath}\" -ar 16000 -ac 1 -c:a pcm_s16le \"{outputPath}\"";
        await RunFFmpegAsync(args);
    }

    public async Task ExtractFrameAsync(string videoPath, TimeSpan timestamp, string outputPath)
    {
        // Extract a single frame at timestamp
        // -ss before -i is faster/seeking
        // Use standard format 00:00:00.000
        var timeStr = timestamp.ToString(@"hh\:mm\:ss\.fff");
        var args = $"-y -ss {timeStr} -i \"{videoPath}\" -frames:v 1 -q:v 2 \"{outputPath}\"";
        await RunFFmpegAsync(args);
    }

    private async Task RunFFmpegAsync(string args)
    {
        var psi = new ProcessStartInfo
        {
            FileName = _ffmpegPath,
            Arguments = args,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        using var process = new Process { StartInfo = psi };
        process.Start();
        
        // We can capture output for logging if needed
        // string output = await process.StandardOutput.ReadToEndAsync();
        // string error = await process.StandardError.ReadToEndAsync();

        await process.WaitForExitAsync();

        if (process.ExitCode != 0)
        {
            throw new Exception($"FFmpeg exited with code {process.ExitCode}. Arguments: {args}");
        }
    }
}