using Microsoft.AspNetCore.Hosting;
using PDFtoImage;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

public class PdfToImageService
{
    private readonly PdfiumBootstrapper _pdfiumBootstrapper;

    public PdfToImageService(IWebHostEnvironment env)
    {
        _pdfiumBootstrapper = new PdfiumBootstrapper(env);
    }

    public async Task<List<string>> ConvertPdfToJpgAsync(string pdfPath, string outputFolder)
    {
        _pdfiumBootstrapper.EnsurePdfiumLoaded();

        var imagePaths = new List<string>();

        try
        {
            Directory.CreateDirectory(outputFolder);

            await Task.Run(() =>
            {
                byte[] pdfBytes = File.ReadAllBytes(pdfPath);

                var options = new RenderOptions
                {
                    Dpi = 300,
                    BackgroundColor = SKColors.White
                };

                var pdfImages = PDFtoImage.Conversion.ToImages(pdfBytes, options: options);

                int pageNumber = 1;
                foreach (var page in pdfImages)
                {
                    var outputPath = Path.Combine(outputFolder, $"page_{pageNumber}.jpg");

                    using (var fileStream = File.Create(outputPath))
                    {
                        page.Encode(fileStream, SKEncodedImageFormat.Jpeg, 90);
                    }

                    imagePaths.Add(outputPath);
                    page.Dispose();
                    pageNumber++;
                }
            });

            return imagePaths;
        }
        catch (Exception ex)
        {
            throw new Exception($"Error converting PDF to images: {ex.Message}", ex);
        }
    }

    public class PdfiumBootstrapper
    {
        private readonly IWebHostEnvironment _env;
        private bool _loaded = false;

        public PdfiumBootstrapper(IWebHostEnvironment env)
        {
            _env = env;
        }

        public void EnsurePdfiumLoaded()
        {
            if (_loaded)
                return;

            var pluginPath = Path.Combine(
                _env.ContentRootPath,
                "Plugins",
                "Misc.FruitBankPlugin" // <- change this
            );

            var archFolder = Environment.Is64BitProcess ? "win-x64" : "win-x86";
            var dllPath = Path.Combine(pluginPath, "runtimes", archFolder, "native", "pdfium.dll");

            if (!File.Exists(dllPath))
                throw new FileNotFoundException($"Pdfium.dll not found: {dllPath}");

            NativeLibrary.Load(dllPath);
            _loaded = true;
        }
    }
}
