using System.Net;
using System.Text.Json;
using System.Diagnostics;

class Program
{
    static async Task Main(string[] args)
    {
        const string inputJsonFile = "animated_images.json"; // JSON file containing video links
        const string outputFolder = "output_videos"; // Folder to save resized videos
        const int targetWidth = 512; // Target width
        const int targetHeight = 512; // Target height

        // Ensure the output folder exists
        Directory.CreateDirectory(outputFolder);

        // Read JSON file
        if (!File.Exists(inputJsonFile))
        {
            Console.WriteLine($"Error: {inputJsonFile} not found.");
            return;
        }

        List<ImageInfo>? videos = await LoadJson(inputJsonFile);

        // Process each video URL
        if (videos == null || videos.Count == 0)
        {
            Console.WriteLine("No videos to process.");
            return;
        }

        Console.WriteLine($"Found {videos.Count} videos. Starting download and resize...");

        using HttpClient httpClient = new HttpClient();
        int videoIndex = 1;

        foreach (var video in videos)
        {
            try
            {
                // Extract filename from URL
                var videoUrl = video.Url;
                var fileName = Path.GetFileName(new Uri(videoUrl).AbsolutePath);

                // Download the video
                Console.WriteLine($"[{videoIndex}/{videos.Count}] Downloading {fileName}...");
                string savedFilePath = Path.Combine(outputFolder, fileName);

                using (var response = await httpClient.GetAsync(videoUrl))
                {
                    response.EnsureSuccessStatusCode();
                    await using (var fs = new FileStream(savedFilePath, FileMode.Create, FileAccess.Write))
                    {
                        await response.Content.CopyToAsync(fs);
                    }
                }

                // Resize the video using FFmpeg
                string resizedFilePath = Path.Combine(outputFolder, $"resized_{fileName}");
                ResizeVideo(savedFilePath, resizedFilePath, targetWidth, targetHeight);

                Console.WriteLine($"Resized video saved to {resizedFilePath}");
                videoIndex++;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error processing video: {ex.Message}");
            }
        }

        Console.WriteLine("Processing complete.");
    }

    /// <summary>
    /// Resize the video using FFmpeg.
    /// </summary>
    static void ResizeVideo(string inputFile, string outputFile, int width, int height)
    {
        var ffmpegPath = "ffmpeg"; // Ensure FFmpeg is installed and available in PATH

        if (!IsFFmpegAvailable())
        {
            Console.WriteLine($"Error: FFmpeg is not installed or not available in PATH.");
            return;
        }

        var arguments = $"-i \"{inputFile}\" -vf \"scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2\" -c:a copy \"{outputFile}\"";

        var ffmpegProcess = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = ffmpegPath,
                Arguments = arguments,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            }
        };

        ffmpegProcess.Start();

        // Print FFmpeg output/errors to the console
        string output = ffmpegProcess.StandardError.ReadToEnd();
        Console.WriteLine(output);

        ffmpegProcess.WaitForExit();
    }

    /// <summary>
    /// Load JSON file into a list of ImageInfo objects.
    /// </summary>
    static async Task<List<ImageInfo>?> LoadJson(string jsonFilePath)
    {
        await using var fs = new FileStream(jsonFilePath, FileMode.Open, FileAccess.Read);
        return await JsonSerializer.DeserializeAsync<List<ImageInfo>>(fs);
    }

    /// <summary>
    /// Checks if FFmpeg is installed and callable from the command line.
    /// </summary>
    static bool IsFFmpegAvailable()
    {
        try
        {
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "ffmpeg",
                    Arguments = "-version",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };
            process.Start();
            process.WaitForExit();
            return process.ExitCode == 0; // FFmpeg is available
        }
        catch
        {
            return false; // FFmpeg is not installed or not in PATH
        }
    }
}

// Class to represent parsed image data
public class ImageInfo
{
    public string Url { get; set; }
    public List<string> Tags { get; set; }
}

make it also split videos to frames and save each video into folder with filename frames should be labeled as frame index