"""Document OCR facade used by the processing pipeline."""

from __future__ import annotations

import logging
from pathlib import Path

from app.services.ocr import OCRResult, get_default_ocr_provider

logger = logging.getLogger(__name__)


def ocr_engine_available() -> bool:
    """True when the configured local OCR provider can run."""
    try:
        return get_default_ocr_provider().available()
    except Exception:
        logger.exception("OCR availability check failed")
        return False


def process_document(file_path: str | Path, mime_type: str | None = None) -> OCRResult:
    """
    Run local OCR + deterministic invoice extraction.

    Never modifies the original file. Returns structured OCRResult;
    field values are null when not confidently detected (no invented data).
    """
    provider = get_default_ocr_provider()
    path = str(file_path)
    logger.info("OCR start provider=%s file=%s mime=%s", provider.name, Path(path).name, mime_type)
    result = provider.process_document(path, mime_type)
    logger.info(
        "OCR done file=%s status=%s engine=%s pages=%s chars=%s confidence=%s",
        Path(path).name,
        result.status,
        result.ocr_engine,
        result.pages,
        len(result.text or ""),
        result.extraction.overall_confidence if result.extraction else None,
    )
    return result
