# pdf_render.py
import io

try:
    import fitz  # PyMuPDF
    _HAS_PYMUPDF = True
except Exception:
    _HAS_PYMUPDF = False
    from pdf2image import convert_from_path

def pdf_page_to_image_bytes(path: str, page_index: int = 0, zoom: float = 2.0, fmt: str = "PNG") -> bytes:
    """
    Zwraca bytes obrazka z jednej strony PDF:
      - PyMuPDF (szybki) jeśli dostępny,
      - inaczej pdf2image + poppler (wymaga 'pdftoppm').
    page_index: 0-based
    """
    if _HAS_PYMUPDF:
        doc = fitz.open(path)
        page = doc.load_page(page_index)
        mat = fitz.Matrix(zoom, zoom)
        pix = page.get_pixmap(matrix=mat, alpha=False)
        return pix.tobytes(fmt.lower())
    # fallback
    images = convert_from_path(path, first_page=page_index+1, last_page=page_index+1, fmt=fmt)
    bio = io.BytesIO()
    images[0].save(bio, fmt)
    return bio.getvalue()
