using System;
using System.IO;
using ImageMagick;

namespace AutoIngest.Engine
{
    /// <summary>
    /// Converts any image format to ecommerce-optimized progressive JPG.
    /// Delegates all format detection to Magick.NET (RAW, HEIC, SVG, standard raster).
    /// </summary>
    public class ImageConverter
    {
        static ImageConverter()
        {
            MagickNET.SetTempDirectory(Path.GetTempPath());
        }

        public void ConvertToJpg(string inputPath, string outputPath,
            int quality = 92)
        {
            using var image = new MagickImage(inputPath);

            // No dimension limit: images are converted at their native resolution.
            // Older cameras (≤20MP) produce reasonably sized output and we don't want
            // to throw away detail by downscaling.

            image.ColorSpace = ColorSpace.sRGB;
            image.Alpha(AlphaOption.Off);

            image.Format = MagickFormat.Jpeg;
            image.Quality = (uint)quality;
            image.Settings.SetDefine("jpeg:optimize-coding", "true");
            image.Settings.SetDefine("jpeg:progressive", "true");
            image.Settings.Interlace = Interlace.Line;

            image.Write(outputPath);
        }

        public bool CanRead(string path)
        {
            try
            {
                _ = new MagickImageInfo(path);
                return true;
            }
            catch (MagickCorruptImageErrorException) { return false; }
            catch (MagickDelegateErrorException) { return false; }
            catch { return false; }
        }
    }
}
