"""Slim tool: extract_documents — Extract text from PDFs, images, and parse tables."""
import json
from typing import Any


def extract_documents(
    file_path: str,
    pages: str = "all",
    parse_tables: bool = True,
    language: str = "eng",
) -> str:
    """Extract text from documents (PDF or image) and optionally parse embedded tables.

    Args:
        file_path: Path to the document file (PDF or image).
        pages: Pages to extract from PDF (default "all", e.g. "1-3").
        parse_tables: Whether to attempt table parsing from extracted text (default True).
        language: OCR language code (default "eng").

    Returns:
        JSON with extracted text and optional parsed tables.
    """
    result: dict[str, Any] = {}
    lower = file_path.lower()

    if lower.endswith(".pdf"):
        from databridge.ingestion import extract_pdf_text
        result["extraction"] = extract_pdf_text(file_path, pages=pages)
    else:
        from databridge.ingestion import ocr_image
        result["extraction"] = ocr_image(file_path, language=language)

    if parse_tables:
        text = ""
        extraction = result.get("extraction", {})
        if isinstance(extraction, dict):
            content = extraction.get("content", [])
            if isinstance(content, list):
                text = "\n".join(item.get("text", "") for item in content if isinstance(item, dict))
            elif isinstance(extraction.get("text"), str):
                text = extraction["text"]

        if text.strip():
            from databridge.ingestion import parse_table_from_text
            result["tables"] = parse_table_from_text(text)

    return json.dumps(result, indent=2, default=str)
