using System.Text;
using System.Text.RegularExpressions;
using UglyToad.PdfPig;

namespace ToolsServices
{
    public static class PdfService
    {
        #region Méthodes publiques
        public static string ExtractPdfFromBytes(byte[] bytes)
        {
            using var ms = new MemoryStream(bytes);
            using var document = UglyToad.PdfPig.PdfDocument.Open(ms);

            var builder = new StringBuilder();

            foreach (var page in document.GetPages())
            {
                builder.AppendLine(page.Text);
            }

            return builder.ToString();
        }



        public static string ExtractTextFromPdf(string fileFullname)
        {
            LoggerService.LogInfo($"PdfService.ExtractTextFromPdf : {fileFullname}");
            var text = new StringBuilder();
            using (var document = PdfDocument.Open(fileFullname))
            {
                foreach (var page in document.GetPages())
                {
                    string texte = NettoyerTexte(page.Text);
                    text.AppendLine(texte);
                }
            }
            return text.ToString();
        }
        #endregion

        public static string NettoyerTexte(string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            // 1. Supprimer les caractères de contrôle ASCII < 32 (sauf retour à la ligne)
            string cleaned = new string(input.Where(c => !char.IsControl(c) || c == '\n' || c == '\r').ToArray());

            // 2. Normaliser les espaces
            cleaned = Regex.Replace(cleaned, @"\s+", " ");

            // 3. Supprimer les coupures de mots (tiret suivi d’espace ou retour ligne)
            cleaned = Regex.Replace(cleaned, @"-\s+", "");

            // 4. Normaliser Unicode pour remettre les accents
            cleaned = cleaned.Normalize(NormalizationForm.FormC);

            // 5. Supprimer les caractères non imprimables restants
            cleaned = new string(cleaned.Where(c => c >= 32).ToArray());

            return cleaned.Trim();
        }

    }
}
