from PyPDF2 import PdfReader
from io import BytesIO
import logging

class ReadPdf:
    @staticmethod
    def read(file_bytes: bytes) -> str:
        """
        Lee y extrae texto de un archivo PDF en formato bytes.
        Maneja errores comunes de PyPDF2 con objetos indirectos.
        """
        try:
            pdf_reader = PdfReader(BytesIO(file_bytes))
            text = ''
            for page_num, page in enumerate(pdf_reader.pages):
                try:
                    page_text = page.extract_text() or ''
                    text += page_text
                except Exception as e:
                    logging.warning(f"Error extrayendo texto de página {page_num + 1}: {str(e)}")
                    # Continúa con las siguientes páginas
                    continue
            return text
        except Exception as e:
            # Si falla completamente, intentar con modo de recuperación
            logging.error(f"Error procesando PDF: {str(e)}")
            try:
                pdf_reader = PdfReader(BytesIO(file_bytes), strict=False)
                text = ''
                for page_num, page in enumerate(pdf_reader.pages):
                    try:
                        page_text = page.extract_text() or ''
                        text += page_text
                    except:
                        # Si falla una página, continuar con las demás
                        continue
                return text
            except Exception as final_error:
                raise Exception(f"No se pudo procesar el PDF: {str(final_error)}")
