"""Extract text content from uploaded files using Docling."""
import os
import tempfile
from typing import Optional

from docling.document_converter import DocumentConverter, PdfFormatOption
from docling.datamodel.base_models import InputFormat
from docling.datamodel.pipeline_options import PdfPipelineOptions


class FileExtractionError(RuntimeError):
    """Raised when file extraction fails."""


class FileExtractor:
    """Extract text from files via Docling."""

    def __init__(self) -> None:
        pdf_options = PdfPipelineOptions(do_ocr=False)
        self._converter = DocumentConverter(
            format_options={
                InputFormat.PDF: PdfFormatOption(pipeline_options=pdf_options)
            }
        )

    def extract_text(self, file_bytes: bytes, filename: str) -> str:
        if not file_bytes:
            raise FileExtractionError("Leere Datei.")

        suffix = ""
        if filename and "." in filename:
            suffix = os.path.splitext(filename)[1]

        try:
            with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
                tmp.write(file_bytes)
                tmp_path = tmp.name

            result = self._converter.convert(tmp_path)
            document = result.document
            text = document.export_to_markdown().strip()
            if not text:
                raise FileExtractionError("Keine Inhalte im Dokument gefunden.")
            return text
        except FileExtractionError:
            raise
        except Exception as exc:
            raise FileExtractionError(f"Datei konnte nicht verarbeitet werden: {exc}") from exc
        finally:
            try:
                if "tmp_path" in locals():
                    os.unlink(tmp_path)
            except Exception:
                pass
