using System;
using System.Diagnostics;
using System.IO;
using System.Configuration;

public static class GhostscriptCompressor
{
    public static string CompressPdf(string inputPath)
    {
        string outputPath = Path.Combine(
            Path.GetDirectoryName(inputPath),
            Path.GetFileNameWithoutExtension(inputPath) + "_compressed.pdf"
        );

        // Ghostscript command arguments for compression

        string gsExe = ConfigurationManager.AppSettings["GhostscriptPath"];
        if (string.IsNullOrEmpty(gsExe) || !File.Exists(gsExe)) {
            Console.WriteLine("Ghostscript executable not found. Check app.config path.", gsExe);
            return null;
        }

        // Ghostscript arguments
        string gsArgs = $"-sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=\"{outputPath}\" \"{inputPath}\"";
        Console.WriteLine(gsArgs);
        ProcessStartInfo psi = new ProcessStartInfo
        {
            FileName = gsExe,
            Arguments = gsArgs,
            CreateNoWindow = true,
            UseShellExecute = false,
            RedirectStandardError = true,
            RedirectStandardOutput = true
        };

        using (Process process = new Process { StartInfo = psi })
        {
            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            process.WaitForExit();

            if (process.ExitCode != 0)
            {
                Console.WriteLine($"Ghostscript failed: {error}");
                return null;
            }
        }
        return outputPath;
    }
}
