"""Adaptador PDF para orquestar prefacturas compuestas."""

from __future__ import annotations

from io import BytesIO

from PyPDF2 import PdfReader, PdfWriter

from app.batch_processing.domain.models import PrefacturaPdfPage


class PyPdfPrefacturaExtractor:
    """Extrae texto por página y reconstruye rangos del PDF original."""

    def extract_pages(self, contents: bytes) -> list[PrefacturaPdfPage]:
        reader = self._reader(contents)
        pages: list[PrefacturaPdfPage] = []
        for index, page in enumerate(reader.pages, start=1):
            try:
                text = page.extract_text() or ""
            except Exception:
                text = ""
            pages.append(PrefacturaPdfPage(page_number=index, text=text))
        return pages

    def build_range_pdf(self, contents: bytes, page_start: int, page_end: int) -> bytes:
        reader = self._reader(contents)
        start_index = max(int(page_start or 1), 1) - 1
        end_index = min(max(int(page_end or page_start), page_start), len(reader.pages))
        writer = PdfWriter()
        for index in range(start_index, end_index):
            writer.add_page(reader.pages[index])
        output = BytesIO()
        writer.write(output)
        return output.getvalue()

    def build_pages_pdf(self, contents: bytes, page_numbers: list[int]) -> bytes:
        reader = self._reader(contents)
        writer = PdfWriter()
        for page_number in page_numbers:
            index = int(page_number or 0) - 1
            if 0 <= index < len(reader.pages):
                writer.add_page(reader.pages[index])
        output = BytesIO()
        writer.write(output)
        return output.getvalue()

    def _reader(self, contents: bytes) -> PdfReader:
        if not contents:
            raise ValueError("El PDF de prefactura está vacío.")
        return PdfReader(BytesIO(contents), strict=False)
