"""OCR 使用的 PDF 文本层提取与页面渲染边界。"""

from __future__ import annotations

import subprocess
from collections.abc import Callable
from pathlib import Path

from app.services.document_preview import DocumentPreviewAssets


def extract_pdf_text_layer(
    pdf_path: Path,
    *,
    timeout_seconds: int,
    normalize: Callable[[str], str],
) -> str:
    try:
        completed = subprocess.run(
            ["pdftotext", "-layout", str(pdf_path), "-"],
            capture_output=True,
            text=True,
            timeout=timeout_seconds,
            check=False,
        )
    except (OSError, subprocess.SubprocessError, UnicodeError):
        return ""
    if completed.returncode != 0:
        return ""
    return normalize(completed.stdout)


def convert_pdf_to_images(
    pdf_path: Path,
    *,
    output_dir: Path,
    timeout_seconds: int,
) -> tuple[list[Path], bool]:
    try:
        pages = DocumentPreviewAssets.render_pdf_pages(
            pdf_path=pdf_path,
            output_dir=output_dir,
            timeout_seconds=timeout_seconds,
        )
    except RuntimeError as exc:
        raise RuntimeError(f"PDF 转图片失败：{exc}") from exc
    return pages, True
