// This file is auto-generated by alef. DO NOT EDIT.
// alef:hash:4e15143f4af1ae8bafbdb1506ef057da924484c66a19483966333558ad437e75
// Re-generate with: alef generate
#![allow(missing_docs)]
#![allow(deprecated, dead_code, unused_imports, unused_variables)]
#![allow(
    clippy::default_trait_access,
    clippy::cast_possible_wrap,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::just_underscores_and_digits,
    clippy::unused_unit,
    clippy::let_unit_value,
    clippy::needless_borrow,
    clippy::too_many_arguments,
    clippy::map_identity,
    clippy::unnecessary_cast,
    clippy::unwrap_or_default,
    clippy::derivable_impls,
    clippy::needless_borrows_for_generic_args,
    clippy::unnecessary_fallible_conversions,
    clippy::useless_conversion,
    clippy::arc_with_non_send_sync,
    clippy::collapsible_if,
    clippy::clone_on_copy,
    clippy::should_implement_trait
)]
#![allow(
    clippy::unsafe_derive_deserialize,
    clippy::must_use_candidate,
    clippy::return_self_not_must_use,
    clippy::use_self,
    clippy::missing_const_for_fn,
    clippy::missing_errors_doc,
    clippy::needless_pass_by_value,
    clippy::doc_markdown,
    clippy::derive_partial_eq_without_eq,
    clippy::uninlined_format_args,
    clippy::redundant_clone,
    clippy::implicit_clone,
    clippy::redundant_closure_for_method_calls,
    clippy::wildcard_imports,
    clippy::option_if_let_else,
    clippy::too_many_lines
)]
#![allow(clippy::multiple_unsafe_ops_per_block)]
#![allow(unsafe_code)]

use async_trait::async_trait;
use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;
use std::collections::HashMap;
use std::sync::Arc;

/// Wrapper for trait visitor types (Py<PyAny>) that implements Clone.
///
/// Py<PyAny> is not Clone. This wrapper uses Arc<Py<PyAny>> internally for cheap cloning.
/// The .inner field is public for compatibility with generated code that needs to access
/// the underlying Py<PyAny> for trait dispatch.
#[derive(Debug)]
pub struct PyVisitorRef {
    pub inner: std::sync::Arc<pyo3::Py<pyo3::PyAny>>,
}

impl Clone for PyVisitorRef {
    fn clone(&self) -> Self {
        PyVisitorRef {
            inner: std::sync::Arc::clone(&self.inner),
        }
    }
}

impl From<pyo3::Py<pyo3::PyAny>> for PyVisitorRef {
    fn from(visitor: pyo3::Py<pyo3::PyAny>) -> Self {
        PyVisitorRef {
            inner: std::sync::Arc::new(visitor),
        }
    }
}

impl<'a, 'py> pyo3::FromPyObject<'a, 'py> for PyVisitorRef {
    type Error = pyo3::PyErr;

    fn extract(ob: pyo3::Borrowed<'a, 'py, pyo3::PyAny>) -> pyo3::PyResult<Self> {
        Ok(PyVisitorRef {
            inner: std::sync::Arc::new(ob.to_owned().unbind()),
        })
    }
}

impl<'py> pyo3::conversion::IntoPyObject<'py> for PyVisitorRef {
    type Target = pyo3::PyAny;
    type Output = pyo3::Bound<'py, pyo3::PyAny>;
    type Error = std::convert::Infallible;

    fn into_pyobject(self, py: pyo3::Python<'py>) -> Result<Self::Output, Self::Error> {
        Ok((*self.inner).bind(py).clone())
    }
}

mod alef_json_str {
    use serde::{Deserialize, Deserializer};
    use serde_json::Value;
    pub fn deserialize<'de, D>(deserializer: D) -> Result<String, D::Error>
    where
        D: Deserializer<'de>,
    {
        let v = Value::deserialize(deserializer)?;
        Ok(match v {
            Value::String(s) => s,
            other => other.to_string(),
        })
    }
}

mod alef_json_str_opt {
    use serde::{Deserialize, Deserializer};
    use serde_json::Value;
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let v: Option<Value> = Option::deserialize(deserializer)?;
        Ok(v.and_then(|val| match val {
            Value::Null => None,
            Value::String(s) => Some(s),
            other => Some(other.to_string()),
        }))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct CacheStats {
    #[pyo3(get)]
    pub total_files: usize,
    #[pyo3(get)]
    pub total_size_mb: f64,
    #[pyo3(get)]
    pub available_space_mb: f64,
    #[pyo3(get)]
    pub oldest_file_age_days: f64,
    #[pyo3(get)]
    pub newest_file_age_days: f64,
}

#[pymethods]
impl CacheStats {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (total_files, total_size_mb, available_space_mb, oldest_file_age_days, newest_file_age_days))]
    #[new]
    pub fn new(
        total_files: usize,
        total_size_mb: f64,
        available_space_mb: f64,
        oldest_file_age_days: f64,
        newest_file_age_days: f64,
    ) -> Self {
        Self {
            total_files,
            total_size_mb,
            available_space_mb,
            oldest_file_age_days,
            newest_file_age_days,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct AccelerationConfig {
    /// Execution provider to use for ONNX inference.
    #[pyo3(get)]
    pub provider: ExecutionProviderType,
    /// GPU device ID (for CUDA/TensorRT). Ignored for CPU/CoreML/Auto.
    #[pyo3(get)]
    pub device_id: u32,
}

#[pymethods]
impl AccelerationConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (provider=Self::default().provider, device_id=Self::default().device_id))]
    #[new]
    pub fn new(provider: ExecutionProviderType, device_id: u32) -> Self {
        Self { provider, device_id }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ContentFilterConfig {
    /// Include running headers in extraction output.
    ///
    /// - PDF: Disables top-margin furniture stripping and prevents the layout
    ///   model from treating `PageHeader`-classified regions as furniture.
    /// - DOCX: Includes document headers in text output.
    /// - RTF/ODT: Headers already included; this is a no-op when true.
    /// - HTML/EPUB: Keeps `<header>` element content.
    ///
    /// Default: `false` (headers are stripped or excluded).
    #[pyo3(get)]
    pub include_headers: bool,
    /// Include running footers in extraction output.
    ///
    /// - PDF: Disables bottom-margin furniture stripping and prevents the layout
    ///   model from treating `PageFooter`-classified regions as furniture.
    /// - DOCX: Includes document footers in text output.
    /// - RTF/ODT: Footers already included; this is a no-op when true.
    /// - HTML/EPUB: Keeps `<footer>` element content.
    ///
    /// Default: `false` (footers are stripped or excluded).
    #[pyo3(get)]
    pub include_footers: bool,
    /// Enable the heuristic cross-page repeating text detector.
    ///
    /// When `true` (default), text that repeats verbatim across a supermajority
    /// of pages is classified as furniture and stripped.  Disable this if brand
    /// names or repeated headings are being incorrectly removed by the heuristic.
    ///
    /// Note: when a layout-detection model is active, the model may independently
    /// classify page-header / page-footer regions as furniture on a per-page basis.
    /// To preserve those regions, set `include_headers = true`, `include_footers = true`,
    /// or both, in addition to disabling this flag.
    ///
    /// Primarily affects PDF extraction.
    ///
    /// Default: `true`.
    #[pyo3(get)]
    pub strip_repeating_text: bool,
    /// Include watermark text in extraction output.
    ///
    /// - PDF: Keeps watermark artifacts and arXiv identifiers.
    /// - Other formats: No effect currently.
    ///
    /// Default: `false` (watermarks are stripped).
    #[pyo3(get)]
    pub include_watermarks: bool,
}

#[pymethods]
impl ContentFilterConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (include_headers=Self::default().include_headers, include_footers=Self::default().include_footers, strip_repeating_text=Self::default().strip_repeating_text, include_watermarks=Self::default().include_watermarks))]
    #[new]
    pub fn new(
        include_headers: bool,
        include_footers: bool,
        strip_repeating_text: bool,
        include_watermarks: bool,
    ) -> Self {
        Self {
            include_headers,
            include_footers,
            strip_repeating_text,
            include_watermarks,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> ContentFilterConfig {
        kreuzberg::ContentFilterConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct EmailConfig {
    /// Windows codepage number to use when an MSG file contains no codepage property.
    /// Defaults to `None`, which falls back to windows-1252.
    ///
    /// If an unrecognized or invalid codepage number is supplied (including 0),
    /// the behavior silently falls back to windows-1252 — the same as when the
    /// MSG file itself contains an unrecognized codepage. No error or warning is
    /// emitted. Users should verify output when supplying unusual values.
    ///
    /// Common values:
    /// - 1250: Central European (Polish, Czech, Hungarian, etc.)
    /// - 1251: Cyrillic (Russian, Ukrainian, Bulgarian, etc.)
    /// - 1252: Western European (default)
    /// - 1253: Greek
    /// - 1254: Turkish
    /// - 1255: Hebrew
    /// - 1256: Arabic
    /// - 932:  Japanese (Shift-JIS)
    /// - 936:  Simplified Chinese (GBK)
    #[pyo3(get)]
    pub msg_fallback_codepage: Option<u32>,
}

#[pymethods]
impl EmailConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (msg_fallback_codepage=None))]
    #[new]
    pub fn new(msg_fallback_codepage: Option<u32>) -> Self {
        Self { msg_fallback_codepage }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ExtractionConfig {
    /// Enable caching of extraction results
    #[pyo3(get)]
    pub use_cache: bool,
    /// Enable quality post-processing
    #[pyo3(get)]
    pub enable_quality_processing: bool,
    /// OCR configuration (None = OCR disabled)
    #[pyo3(get)]
    #[serde(skip)]
    pub ocr: Option<OcrConfig>,
    /// Force OCR even for searchable PDFs
    #[pyo3(get)]
    pub force_ocr: bool,
    /// Force OCR on specific pages only (1-indexed page numbers, must be >= 1).
    ///
    /// When set, only the listed pages are OCR'd regardless of text layer quality.
    /// Unlisted pages use native text extraction. Ignored when `force_ocr` is `true`.
    /// Only applies to PDF documents. Duplicates are automatically deduplicated.
    /// An `ocr` config is recommended for backend/language selection; defaults are used if absent.
    #[pyo3(get)]
    pub force_ocr_pages: Option<Vec<u32>>,
    /// Disable OCR entirely, even for images.
    ///
    /// When `true`, OCR is skipped for all document types. Images return metadata
    /// only (dimensions, format, EXIF) without text extraction. PDFs use only
    /// native text extraction without OCR fallback.
    ///
    /// Cannot be `true` simultaneously with `force_ocr`.
    ///
    /// *Added in v4.7.0.*
    #[pyo3(get)]
    pub disable_ocr: bool,
    /// Text chunking configuration (None = chunking disabled)
    #[pyo3(get)]
    #[serde(skip)]
    pub chunking: Option<ChunkingConfig>,
    /// Content filtering configuration (None = use extractor defaults).
    ///
    /// Controls whether document "furniture" (headers, footers, watermarks,
    /// repeating text) is included in or stripped from extraction results.
    /// See [`ContentFilterConfig`] for per-field documentation.
    #[pyo3(get)]
    pub content_filter: Option<ContentFilterConfig>,
    /// Image extraction configuration (None = no image extraction)
    #[pyo3(get)]
    pub images: Option<ImageExtractionConfig>,
    /// PDF-specific options (None = use defaults)
    #[pyo3(get)]
    pub pdf_options: Option<PdfConfig>,
    /// Token reduction configuration (None = no token reduction)
    #[pyo3(get)]
    pub token_reduction: Option<TokenReductionOptions>,
    /// Language detection configuration (None = no language detection)
    #[pyo3(get)]
    pub language_detection: Option<LanguageDetectionConfig>,
    /// Page extraction configuration (None = no page tracking)
    #[pyo3(get)]
    pub pages: Option<PageConfig>,
    /// Keyword extraction configuration (None = no keyword extraction)
    #[pyo3(get)]
    pub keywords: Option<KeywordConfig>,
    /// Post-processor configuration (None = use defaults)
    #[pyo3(get)]
    pub postprocessor: Option<PostProcessorConfig>,
    /// HTML to Markdown conversion options (None = use defaults)
    ///
    /// Configure how HTML documents are converted to Markdown, including heading styles,
    /// list formatting, code block styles, and preprocessing options.
    #[pyo3(get)]
    #[serde(skip)]
    pub html_options: Option<String>,
    /// Styled HTML output configuration.
    ///
    /// When set alongside `output_format = OutputFormat::Html`, the extraction
    /// pipeline uses [`StyledHtmlRenderer`](crate::rendering::StyledHtmlRenderer)
    /// which emits stable `kb-*` CSS class hooks on every structural element
    /// and optionally embeds theme CSS or user-supplied CSS in a `<style>` block.
    ///
    /// When `None`, the existing plain comrak-based HTML renderer is used.
    #[pyo3(get)]
    pub html_output: Option<HtmlOutputConfig>,
    /// Default per-file timeout in seconds for batch extraction.
    ///
    /// When set, each file in a batch will be canceled after this duration
    /// unless overridden by [`FileExtractionConfig::timeout_secs`].
    ///
    /// Defaults to `Some(60)` to prevent pathological files (e.g. deeply
    /// nested archives, documents with millions of cells) from running
    /// indefinitely and exhausting caller resources. Set to `None` to
    /// disable the timeout for trusted input or long-running workloads.
    #[pyo3(get)]
    pub extraction_timeout_secs: Option<u64>,
    /// Maximum concurrent extractions in batch operations (None = (num_cpus × 1.5).ceil()).
    ///
    /// Limits parallelism to prevent resource exhaustion when processing
    /// large batches. Defaults to (num_cpus × 1.5).ceil() when not set.
    #[pyo3(get)]
    pub max_concurrent_extractions: Option<usize>,
    /// Result structure format
    ///
    /// Controls whether results are returned in unified format (default) with all
    /// content in the `content` field, or element-based format with semantic
    /// elements (for Unstructured-compatible output).
    #[pyo3(get)]
    pub result_format: ResultFormat,
    /// Security limits for archive extraction.
    ///
    /// Controls maximum archive size, compression ratio, file count, and other
    /// security thresholds to prevent decompression bomb attacks. Also caps
    /// nesting depth, iteration count, entity / token length, total
    /// content size, and table cell count for every extraction path that
    /// ingests user-controlled bytes.
    /// When `None`, default limits are used.
    #[pyo3(get)]
    pub security_limits: Option<SecurityLimits>,
    /// Maximum uncompressed size in bytes for a single embedded file before
    /// recursive extraction is attempted (default: 50 MiB).
    ///
    /// Applies to embedded objects inside OOXML containers (DOCX, PPTX) and
    /// to email attachments processed via recursive extraction. Files that
    /// exceed this limit are skipped with a `ProcessingWarning` rather than
    /// passed to the extraction pipeline, preventing a single oversized
    /// embedded object from consuming unbounded memory or time.
    ///
    /// Set to `None` to disable the per-embedded-file cap (falls back to
    /// `security_limits.max_archive_size` as the only guard).
    #[pyo3(get)]
    pub max_embedded_file_bytes: Option<u64>,
    /// Content text format (default: Plain).
    ///
    /// Controls the format of the extracted content:
    /// - `Plain`: Raw extracted text (default)
    /// - `Markdown`: Markdown formatted output
    /// - `Djot`: Djot markup format (requires djot feature)
    /// - `Html`: HTML formatted output
    ///
    /// When set to a structured format, extraction results will include
    /// formatted output. The `formatted_content` field may be populated
    /// when format conversion is applied.
    #[pyo3(get)]
    pub output_format: OutputFormat,
    /// Layout detection configuration (None = layout detection disabled).
    ///
    /// When set, PDF pages and images are analyzed for document structure
    /// (headings, code, formulas, tables, figures, etc.) using RT-DETR models
    /// via ONNX Runtime. For PDFs, layout hints override paragraph classification
    /// in the markdown pipeline. For images, per-region OCR is performed with
    /// markdown formatting based on detected layout classes.
    /// Requires the `layout-detection` feature to run inference; the field is
    /// present whenever the `layout-types` feature is active (which includes
    /// `layout-detection` as well as the no-ORT target groups).
    #[pyo3(get)]
    pub layout: Option<LayoutDetectionConfig>,
    /// Run layout detection on the non-OCR PDF markdown path.
    ///
    /// When `true` and `layout` is `Some(_)`, layout regions inform heading,
    /// table, list, and figure detection in the structure pipeline that would
    /// otherwise rely on font-clustering heuristics alone. Significantly
    /// improves SF1 (structural F1) at the cost of inference latency
    /// (~150-300ms/page CPU, ~20-50ms/page GPU). Default: `false`.
    /// Requires the `layout-detection` feature.
    #[pyo3(get)]
    pub use_layout_for_markdown: bool,
    /// Enable structured document tree output.
    ///
    /// When true, populates the `document` field on `ExtractionResult` with a
    /// hierarchical `DocumentStructure` containing heading-driven section nesting,
    /// table grids, content layer classification, and inline annotations.
    ///
    /// Independent of `result_format` — can be combined with Unified or ElementBased.
    #[pyo3(get)]
    pub include_document_structure: bool,
    /// Hardware acceleration configuration for ONNX Runtime models.
    ///
    /// Controls execution provider selection for layout detection and embedding
    /// models. When `None`, uses platform defaults (CoreML on macOS, CUDA on
    /// Linux, CPU on Windows).
    #[pyo3(get)]
    pub acceleration: Option<AccelerationConfig>,
    /// Cache namespace for tenant isolation.
    ///
    /// When set, cache entries are stored under `{cache_dir}/{namespace}/`.
    /// Must be alphanumeric, hyphens, or underscores only (max 64 chars).
    /// Different namespaces have isolated cache spaces on the same filesystem.
    #[pyo3(get)]
    pub cache_namespace: Option<String>,
    /// Per-request cache TTL in seconds.
    ///
    /// Overrides the global `max_age_days` for this specific extraction.
    /// When `0`, caching is completely skipped (no read or write).
    /// When `None`, the global TTL applies.
    #[pyo3(get)]
    pub cache_ttl_secs: Option<u64>,
    /// Email extraction configuration (None = use defaults).
    ///
    /// Currently supports configuring the fallback codepage for MSG files
    /// that do not specify one. See `EmailConfig` for details.
    #[pyo3(get)]
    pub email: Option<EmailConfig>,
    /// Concurrency limits for constrained environments (None = use defaults).
    ///
    /// Controls Rayon thread pool size, ONNX Runtime intra-op threads, and
    /// (when `max_concurrent_extractions` is unset) the batch concurrency
    /// semaphore. See `ConcurrencyConfig` for details.
    #[pyo3(get)]
    #[serde(skip)]
    pub concurrency: Option<String>,
    /// Maximum recursion depth for archive extraction (default: 3).
    /// Set to 0 to disable recursive extraction (legacy behavior).
    #[pyo3(get)]
    pub max_archive_depth: usize,
    /// Tree-sitter language pack configuration (None = tree-sitter disabled).
    ///
    /// When set, enables code file extraction using tree-sitter parsers.
    /// Controls grammar download behavior and code analysis options.
    #[pyo3(get)]
    pub tree_sitter: Option<TreeSitterConfig>,
    /// Structured extraction via LLM (None = disabled).
    ///
    /// When set, the extracted document content is sent to an LLM with the
    /// provided JSON schema. The structured response is stored in
    /// `ExtractionResult::structured_output`.
    #[pyo3(get)]
    pub structured_extraction: Option<StructuredExtractionConfig>,
    /// Cancellation token for this extraction (None = no external cancellation).
    ///
    /// Pass a [`CancellationToken`] clone here and call [`CancellationToken::cancel`]
    /// from another thread / task to abort the extraction in progress. The extractor
    /// checks the token at safe checkpoints (before lock acquisition, between pages,
    /// between batch items) and returns [`KreuzbergError::Cancelled`] when set.
    ///
    /// The field is excluded from serialization because `CancellationToken` is a
    /// runtime handle, not a configuration value.
    #[pyo3(get)]
    #[serde(skip)]
    pub cancel_token: Option<String>,
}

#[pymethods]
impl ExtractionConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (use_cache=Self::default().use_cache, enable_quality_processing=Self::default().enable_quality_processing, force_ocr=Self::default().force_ocr, disable_ocr=Self::default().disable_ocr, result_format=Self::default().result_format, output_format=Self::default().output_format, use_layout_for_markdown=Self::default().use_layout_for_markdown, include_document_structure=Self::default().include_document_structure, max_archive_depth=Self::default().max_archive_depth, ocr=None, force_ocr_pages=None, chunking=None, content_filter=None, images=None, pdf_options=None, token_reduction=None, language_detection=None, pages=None, keywords=None, postprocessor=None, html_options=None, html_output=None, extraction_timeout_secs=None, max_concurrent_extractions=None, security_limits=None, max_embedded_file_bytes=None, layout=None, acceleration=None, cache_namespace=None, cache_ttl_secs=None, email=None, concurrency=None, tree_sitter=None, structured_extraction=None, cancel_token=None))]
    #[new]
    pub fn new(
        use_cache: bool,
        enable_quality_processing: bool,
        force_ocr: bool,
        disable_ocr: bool,
        result_format: ResultFormat,
        output_format: OutputFormat,
        use_layout_for_markdown: bool,
        include_document_structure: bool,
        max_archive_depth: usize,
        ocr: Option<OcrConfig>,
        force_ocr_pages: Option<Vec<u32>>,
        chunking: Option<ChunkingConfig>,
        content_filter: Option<ContentFilterConfig>,
        images: Option<ImageExtractionConfig>,
        pdf_options: Option<PdfConfig>,
        token_reduction: Option<TokenReductionOptions>,
        language_detection: Option<LanguageDetectionConfig>,
        pages: Option<PageConfig>,
        keywords: Option<KeywordConfig>,
        postprocessor: Option<PostProcessorConfig>,
        html_options: Option<String>,
        html_output: Option<HtmlOutputConfig>,
        extraction_timeout_secs: Option<u64>,
        max_concurrent_extractions: Option<usize>,
        security_limits: Option<SecurityLimits>,
        max_embedded_file_bytes: Option<u64>,
        layout: Option<LayoutDetectionConfig>,
        acceleration: Option<AccelerationConfig>,
        cache_namespace: Option<String>,
        cache_ttl_secs: Option<u64>,
        email: Option<EmailConfig>,
        concurrency: Option<String>,
        tree_sitter: Option<TreeSitterConfig>,
        structured_extraction: Option<StructuredExtractionConfig>,
        cancel_token: Option<String>,
    ) -> Self {
        Self {
            use_cache,
            enable_quality_processing,
            ocr,
            force_ocr,
            force_ocr_pages,
            disable_ocr,
            chunking,
            content_filter,
            images,
            pdf_options,
            token_reduction,
            language_detection,
            pages,
            keywords,
            postprocessor,
            html_options,
            html_output,
            extraction_timeout_secs,
            max_concurrent_extractions,
            result_format,
            security_limits,
            max_embedded_file_bytes,
            output_format,
            layout,
            use_layout_for_markdown,
            include_document_structure,
            acceleration,
            cache_namespace,
            cache_ttl_secs,
            email,
            concurrency,
            max_archive_depth,
            tree_sitter,
            structured_extraction,
            cancel_token,
        }
    }

    #[pyo3(signature = ())]
    pub fn needs_image_processing(&self) -> bool {
        #[allow(clippy::needless_update)]
        let core_self = kreuzberg::ExtractionConfig {
            use_cache: self.use_cache,

            enable_quality_processing: self.enable_quality_processing,

            ocr: self.ocr.clone().map(Into::into),

            force_ocr: self.force_ocr,

            force_ocr_pages: self.force_ocr_pages.clone(),

            disable_ocr: self.disable_ocr,

            chunking: self.chunking.clone().map(Into::into),

            content_filter: self.content_filter.clone().map(Into::into),

            images: self.images.clone().map(Into::into),

            token_reduction: self.token_reduction.clone().map(Into::into),

            language_detection: self.language_detection.clone().map(Into::into),

            pages: self.pages.clone().map(Into::into),

            postprocessor: self.postprocessor.clone().map(Into::into),

            extraction_timeout_secs: self.extraction_timeout_secs,

            max_concurrent_extractions: self.max_concurrent_extractions,

            result_format: self.result_format.clone().into(),

            security_limits: self.security_limits.clone().map(Into::into),

            max_embedded_file_bytes: self.max_embedded_file_bytes,

            output_format: self.output_format.clone().into(),

            use_layout_for_markdown: self.use_layout_for_markdown,

            include_document_structure: self.include_document_structure,

            acceleration: self.acceleration.clone().map(Into::into),

            cache_namespace: self.cache_namespace.clone(),

            cache_ttl_secs: self.cache_ttl_secs,

            email: self.email.clone().map(Into::into),

            concurrency: Default::default(),

            max_archive_depth: self.max_archive_depth,

            structured_extraction: self.structured_extraction.clone().map(Into::into),

            cancel_token: Default::default(),

            ..Default::default()
        };
        core_self.needs_image_processing()
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> ExtractionConfig {
        kreuzberg::ExtractionConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct FileExtractionConfig {
    /// Override quality post-processing for this file.
    #[pyo3(get)]
    pub enable_quality_processing: Option<bool>,
    /// Override OCR configuration for this file (None in the Option = use batch default).
    #[pyo3(get)]
    #[serde(skip)]
    pub ocr: Option<OcrConfig>,
    /// Override force OCR for this file.
    #[pyo3(get)]
    pub force_ocr: Option<bool>,
    /// Override force OCR pages for this file (1-indexed page numbers).
    #[pyo3(get)]
    pub force_ocr_pages: Option<Vec<u32>>,
    /// Override disable OCR for this file.
    #[pyo3(get)]
    pub disable_ocr: Option<bool>,
    /// Override chunking configuration for this file.
    #[pyo3(get)]
    #[serde(skip)]
    pub chunking: Option<ChunkingConfig>,
    /// Override content filtering configuration for this file.
    #[pyo3(get)]
    pub content_filter: Option<ContentFilterConfig>,
    /// Override image extraction configuration for this file.
    #[pyo3(get)]
    pub images: Option<ImageExtractionConfig>,
    /// Override PDF options for this file.
    #[pyo3(get)]
    pub pdf_options: Option<PdfConfig>,
    /// Override token reduction for this file.
    #[pyo3(get)]
    pub token_reduction: Option<TokenReductionOptions>,
    /// Override language detection for this file.
    #[pyo3(get)]
    pub language_detection: Option<LanguageDetectionConfig>,
    /// Override page extraction for this file.
    #[pyo3(get)]
    pub pages: Option<PageConfig>,
    /// Override keyword extraction for this file.
    #[pyo3(get)]
    pub keywords: Option<KeywordConfig>,
    /// Override post-processor for this file.
    #[pyo3(get)]
    pub postprocessor: Option<PostProcessorConfig>,
    /// Override HTML conversion options for this file.
    #[pyo3(get)]
    #[serde(skip)]
    pub html_options: Option<String>,
    /// Override result format for this file.
    #[pyo3(get)]
    pub result_format: Option<ResultFormat>,
    /// Override output content format for this file.
    #[pyo3(get)]
    pub output_format: Option<OutputFormat>,
    /// Override document structure output for this file.
    #[pyo3(get)]
    pub include_document_structure: Option<bool>,
    /// Override layout detection for this file.
    #[pyo3(get)]
    pub layout: Option<LayoutDetectionConfig>,
    /// Override per-file extraction timeout in seconds.
    ///
    /// When set, the extraction for this file will be canceled after the
    /// specified duration. A timed-out file produces an error result without
    /// affecting other files in the batch.
    #[pyo3(get)]
    pub timeout_secs: Option<u64>,
    /// Override tree-sitter configuration for this file.
    #[pyo3(get)]
    pub tree_sitter: Option<TreeSitterConfig>,
    /// Override structured extraction configuration for this file.
    ///
    /// When set, enables LLM-based structured extraction with a JSON schema
    /// for this specific file. The extracted content is sent to a VLM/LLM
    /// and the response is parsed according to the provided schema.
    #[pyo3(get)]
    pub structured_extraction: Option<StructuredExtractionConfig>,
}

#[pymethods]
impl FileExtractionConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (enable_quality_processing=None, ocr=None, force_ocr=None, force_ocr_pages=None, disable_ocr=None, chunking=None, content_filter=None, images=None, pdf_options=None, token_reduction=None, language_detection=None, pages=None, keywords=None, postprocessor=None, html_options=None, result_format=None, output_format=None, include_document_structure=None, layout=None, timeout_secs=None, tree_sitter=None, structured_extraction=None))]
    #[new]
    pub fn new(
        enable_quality_processing: Option<bool>,
        ocr: Option<OcrConfig>,
        force_ocr: Option<bool>,
        force_ocr_pages: Option<Vec<u32>>,
        disable_ocr: Option<bool>,
        chunking: Option<ChunkingConfig>,
        content_filter: Option<ContentFilterConfig>,
        images: Option<ImageExtractionConfig>,
        pdf_options: Option<PdfConfig>,
        token_reduction: Option<TokenReductionOptions>,
        language_detection: Option<LanguageDetectionConfig>,
        pages: Option<PageConfig>,
        keywords: Option<KeywordConfig>,
        postprocessor: Option<PostProcessorConfig>,
        html_options: Option<String>,
        result_format: Option<ResultFormat>,
        output_format: Option<OutputFormat>,
        include_document_structure: Option<bool>,
        layout: Option<LayoutDetectionConfig>,
        timeout_secs: Option<u64>,
        tree_sitter: Option<TreeSitterConfig>,
        structured_extraction: Option<StructuredExtractionConfig>,
    ) -> Self {
        Self {
            enable_quality_processing,
            ocr,
            force_ocr,
            force_ocr_pages,
            disable_ocr,
            chunking,
            content_filter,
            images,
            pdf_options,
            token_reduction,
            language_detection,
            pages,
            keywords,
            postprocessor,
            html_options,
            result_format,
            output_format,
            include_document_structure,
            layout,
            timeout_secs,
            tree_sitter,
            structured_extraction,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct BatchBytesItem {
    /// The content bytes to extract from
    #[pyo3(get)]
    pub content: Vec<u8>,
    /// MIME type of the content (e.g., "application/pdf", "text/html")
    #[pyo3(get)]
    pub mime_type: String,
    /// Per-item configuration overrides (None uses batch-level defaults)
    #[pyo3(get)]
    #[serde(skip)]
    pub config: Option<FileExtractionConfig>,
}

#[pymethods]
impl BatchBytesItem {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content, mime_type, config=None))]
    #[new]
    pub fn new(content: Vec<u8>, mime_type: String, config: Option<FileExtractionConfig>) -> Self {
        Self {
            content,
            mime_type,
            config,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct BatchFileItem {
    /// Path to the file to extract from
    #[pyo3(get)]
    pub path: String,
    /// Per-file configuration overrides (None uses batch-level defaults)
    #[pyo3(get)]
    #[serde(skip)]
    pub config: Option<FileExtractionConfig>,
}

#[pymethods]
impl BatchFileItem {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (path, config=None))]
    #[new]
    pub fn new(path: String, config: Option<FileExtractionConfig>) -> Self {
        Self { path, config }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct ImageExtractionConfig {
    /// Extract images from documents
    #[pyo3(get)]
    pub extract_images: bool,
    /// Target DPI for image normalization
    #[pyo3(get)]
    pub target_dpi: i32,
    /// Maximum dimension for images (width or height)
    #[pyo3(get)]
    pub max_image_dimension: i32,
    /// Whether to inject image reference placeholders into markdown output.
    /// When `true` (default), image references like `![Image 1](embedded:p1_i0)`
    /// are appended to the markdown. Set to `false` to extract images as data
    /// without polluting the markdown output.
    #[pyo3(get)]
    pub inject_placeholders: bool,
    /// Automatically adjust DPI based on image content
    #[pyo3(get)]
    pub auto_adjust_dpi: bool,
    /// Minimum DPI threshold
    #[pyo3(get)]
    pub min_dpi: i32,
    /// Maximum DPI threshold
    #[pyo3(get)]
    pub max_dpi: i32,
    /// Maximum number of image objects to extract per PDF page.
    ///
    /// Some PDFs (e.g. technical diagrams stored as thousands of raster fragments)
    /// can trigger extremely long or indefinite extraction times when every image
    /// object on a dense page is decoded individually via the PDF extractor. Setting this
    /// limit causes kreuzberg to stop collecting individual images once the count
    /// per page reaches the cap and emit a warning instead.
    ///
    /// `None` (default) means no limit — all images are extracted.
    #[pyo3(get)]
    pub max_images_per_page: Option<u32>,
    /// When `true` (default), extracted images are classified by kind and grouped
    /// into clusters where they appear to belong to one figure.
    #[pyo3(get)]
    pub classify: bool,
    /// When `true`, full-page renders produced during OCR preprocessing are captured
    /// and returned as `ImageKind::PageRaster` entries in `ExtractionResult.images`.
    ///
    /// **PDF + OCR only.** No rasters are captured for non-PDF inputs or when the
    /// document-level OCR bypass is active (whole-document backend). When OCR is
    /// enabled and this flag is set but the active backend skips per-page rendering,
    /// a `ProcessingWarning` is emitted in `ExtractionResult.processing_warnings`.
    ///
    /// Defaults to `false`. Enable when downstream consumers need page thumbnails
    /// (e.g. citation previews, visual grounding).
    #[pyo3(get)]
    pub include_page_rasters: bool,
    /// Run OCR on extracted images and include the recognized text in the document content.
    ///
    /// When `true` (default) and `ExtractionConfig.ocr` is configured, extracted images
    /// are processed with the configured OCR backend. Set to `false` to extract images
    /// without OCR processing, even when OCR is enabled.
    #[pyo3(get)]
    pub run_ocr_on_images: bool,
    /// When `true`, image OCR results are rendered as plain text without the
    /// `![...](...)` markdown placeholder. Only takes effect when `run_ocr_on_images`
    /// is also `true`.
    #[pyo3(get)]
    pub ocr_text_only: bool,
    /// When `true` and `ocr_text_only` is `false`, append the OCR text after
    /// the image placeholder in the rendered output.
    #[pyo3(get)]
    pub append_ocr_text: bool,
}

#[pymethods]
impl ImageExtractionConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (extract_images=Self::default().extract_images, target_dpi=Self::default().target_dpi, max_image_dimension=Self::default().max_image_dimension, inject_placeholders=Self::default().inject_placeholders, auto_adjust_dpi=Self::default().auto_adjust_dpi, min_dpi=Self::default().min_dpi, max_dpi=Self::default().max_dpi, classify=Self::default().classify, include_page_rasters=Self::default().include_page_rasters, run_ocr_on_images=Self::default().run_ocr_on_images, ocr_text_only=Self::default().ocr_text_only, append_ocr_text=Self::default().append_ocr_text, max_images_per_page=None))]
    #[new]
    pub fn new(
        extract_images: bool,
        target_dpi: i32,
        max_image_dimension: i32,
        inject_placeholders: bool,
        auto_adjust_dpi: bool,
        min_dpi: i32,
        max_dpi: i32,
        classify: bool,
        include_page_rasters: bool,
        run_ocr_on_images: bool,
        ocr_text_only: bool,
        append_ocr_text: bool,
        max_images_per_page: Option<u32>,
    ) -> Self {
        Self {
            extract_images,
            target_dpi,
            max_image_dimension,
            inject_placeholders,
            auto_adjust_dpi,
            min_dpi,
            max_dpi,
            max_images_per_page,
            classify,
            include_page_rasters,
            run_ocr_on_images,
            ocr_text_only,
            append_ocr_text,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> ImageExtractionConfig {
        kreuzberg::ImageExtractionConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct TokenReductionOptions {
    /// Reduction mode: "off", "light", "moderate", "aggressive", "maximum"
    #[pyo3(get)]
    pub mode: String,
    /// Preserve important words (capitalized, technical terms)
    #[pyo3(get)]
    pub preserve_important_words: bool,
}

#[pymethods]
impl TokenReductionOptions {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (mode=Self::default().mode, preserve_important_words=Self::default().preserve_important_words))]
    #[new]
    pub fn new(mode: String, preserve_important_words: bool) -> Self {
        Self {
            mode,
            preserve_important_words,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> TokenReductionOptions {
        kreuzberg::TokenReductionOptions::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct LanguageDetectionConfig {
    /// Enable language detection
    #[pyo3(get)]
    pub enabled: bool,
    /// Minimum confidence threshold (0.0-1.0)
    #[pyo3(get)]
    pub min_confidence: f64,
    /// Detect multiple languages in the document
    #[pyo3(get)]
    pub detect_multiple: bool,
}

#[pymethods]
impl LanguageDetectionConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (enabled=Self::default().enabled, min_confidence=Self::default().min_confidence, detect_multiple=Self::default().detect_multiple))]
    #[new]
    pub fn new(enabled: bool, min_confidence: f64, detect_multiple: bool) -> Self {
        Self {
            enabled,
            min_confidence,
            detect_multiple,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> LanguageDetectionConfig {
        kreuzberg::LanguageDetectionConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct HtmlOutputConfig {
    /// Inline CSS string injected into the output after the theme stylesheet.
    /// Concatenated after `css_file` content when both are set.
    #[pyo3(get)]
    pub css: Option<String>,
    /// Path to a CSS file loaded once at renderer construction time.
    /// Concatenated before `css` when both are set.
    #[pyo3(get)]
    pub css_file: Option<String>,
    /// Built-in colour/typography theme. Default: [`HtmlTheme::Unstyled`].
    #[pyo3(get)]
    pub theme: HtmlTheme,
    /// CSS class prefix applied to every emitted class name.
    ///
    /// Default: `"kb-"`. Change this if your host application already uses
    /// classes that start with `kb-`.
    #[pyo3(get)]
    pub class_prefix: String,
    /// When `true` (default), write the resolved CSS into a `<style>` block
    /// immediately after the opening `<div class="{prefix}doc">`.
    ///
    /// Set to `false` to emit only the structural markup and wire up your
    /// own stylesheet targeting the `kb-*` class names.
    #[pyo3(get)]
    pub embed_css: bool,
}

#[pymethods]
impl HtmlOutputConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (theme=Self::default().theme, class_prefix=Self::default().class_prefix, embed_css=Self::default().embed_css, css=None, css_file=None))]
    #[new]
    pub fn new(
        theme: HtmlTheme,
        class_prefix: String,
        embed_css: bool,
        css: Option<String>,
        css_file: Option<String>,
    ) -> Self {
        Self {
            css,
            css_file,
            theme,
            class_prefix,
            embed_css,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> HtmlOutputConfig {
        kreuzberg::HtmlOutputConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct LayoutDetectionConfig {
    /// Confidence threshold override (None = use model default).
    #[pyo3(get)]
    pub confidence_threshold: Option<f32>,
    /// Whether to apply postprocessing heuristics (default: true).
    #[pyo3(get)]
    pub apply_heuristics: bool,
    /// Table structure recognition model.
    ///
    /// Controls which model is used for table cell detection within layout-detected
    /// table regions. Defaults to [`TableModel::Tatr`].
    #[pyo3(get)]
    pub table_model: TableModel,
    /// Hardware acceleration for ONNX models (layout detection + table structure).
    ///
    /// When set, controls which execution provider (CPU, CUDA, CoreML, TensorRT)
    /// is used for inference. Defaults to `None` (auto-select per platform).
    #[pyo3(get)]
    pub acceleration: Option<AccelerationConfig>,
}

#[pymethods]
impl LayoutDetectionConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (apply_heuristics=Self::default().apply_heuristics, table_model=Self::default().table_model, confidence_threshold=None, acceleration=None))]
    #[new]
    pub fn new(
        apply_heuristics: bool,
        table_model: TableModel,
        confidence_threshold: Option<f32>,
        acceleration: Option<AccelerationConfig>,
    ) -> Self {
        Self {
            confidence_threshold,
            apply_heuristics,
            table_model,
            acceleration,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> LayoutDetectionConfig {
        kreuzberg::LayoutDetectionConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct LlmConfig {
    /// Provider/model string using liter-llm routing format.
    ///
    /// Examples: `"openai/gpt-4o"`, `"anthropic/claude-sonnet-4-20250514"`,
    /// `"groq/llama-3.1-70b-versatile"`.
    #[pyo3(get)]
    pub model: String,
    /// API key for the provider. When `None`, liter-llm falls back to
    /// the provider's standard environment variable (e.g., `OPENAI_API_KEY`).
    #[pyo3(get)]
    pub api_key: Option<String>,
    /// Custom base URL override for the provider endpoint.
    #[pyo3(get)]
    pub base_url: Option<String>,
    /// Request timeout in seconds (default: 60).
    #[pyo3(get)]
    pub timeout_secs: Option<u64>,
    /// Maximum retry attempts (default: 3).
    #[pyo3(get)]
    pub max_retries: Option<u32>,
    /// Sampling temperature for generation tasks.
    #[pyo3(get)]
    pub temperature: Option<f64>,
    /// Maximum tokens to generate.
    #[pyo3(get)]
    pub max_tokens: Option<u64>,
}

#[pymethods]
impl LlmConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (model=Self::default().model, api_key=None, base_url=None, timeout_secs=None, max_retries=None, temperature=None, max_tokens=None))]
    #[new]
    pub fn new(
        model: String,
        api_key: Option<String>,
        base_url: Option<String>,
        timeout_secs: Option<u64>,
        max_retries: Option<u32>,
        temperature: Option<f64>,
        max_tokens: Option<u64>,
    ) -> Self {
        Self {
            model,
            api_key,
            base_url,
            timeout_secs,
            max_retries,
            temperature,
            max_tokens,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct StructuredExtractionConfig {
    /// JSON Schema defining the desired output structure.
    #[pyo3(get)]
    #[serde(default, deserialize_with = "alef_json_str::deserialize")]
    pub schema: String,
    /// Schema name passed to the LLM's structured output mode.
    #[pyo3(get)]
    pub schema_name: String,
    /// Optional schema description for the LLM.
    #[pyo3(get)]
    pub schema_description: Option<String>,
    /// Enable strict mode — output must exactly match the schema.
    #[pyo3(get)]
    pub strict: bool,
    /// Custom Jinja2 extraction prompt template. When `None`, a default template is used.
    ///
    /// Available template variables:
    /// - `{{ content }}` — The extracted document text.
    /// - `{{ schema }}` — The JSON schema as a formatted string.
    /// - `{{ schema_name }}` — The schema name.
    /// - `{{ schema_description }}` — The schema description (may be empty).
    #[pyo3(get)]
    pub prompt: Option<String>,
    /// LLM configuration for the extraction.
    #[pyo3(get)]
    pub llm: LlmConfig,
}

#[pymethods]
impl StructuredExtractionConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (schema, schema_name, strict, llm, schema_description=None, prompt=None))]
    #[new]
    pub fn new(
        schema: String,
        schema_name: String,
        strict: bool,
        llm: LlmConfig,
        schema_description: Option<String>,
        prompt: Option<String>,
    ) -> Self {
        Self {
            schema,
            schema_name,
            schema_description,
            strict,
            prompt,
            llm,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OcrQualityThresholds {
    /// Minimum total non-whitespace characters to consider text substantive.
    #[pyo3(get)]
    pub min_total_non_whitespace: usize,
    /// Minimum non-whitespace characters per page on average.
    #[pyo3(get)]
    pub min_non_whitespace_per_page: f64,
    /// Minimum character count for a word to be "meaningful".
    #[pyo3(get)]
    pub min_meaningful_word_len: usize,
    /// Minimum count of meaningful words before text is accepted.
    #[pyo3(get)]
    pub min_meaningful_words: usize,
    /// Minimum alphanumeric ratio (non-whitespace chars that are alphanumeric).
    #[pyo3(get)]
    pub min_alnum_ratio: f64,
    /// Minimum Unicode replacement characters (U+FFFD) to trigger OCR fallback.
    #[pyo3(get)]
    pub min_garbage_chars: usize,
    /// Maximum fraction of short (1-2 char) words before text is considered fragmented.
    #[pyo3(get)]
    pub max_fragmented_word_ratio: f64,
    /// Critical fragmentation threshold — triggers OCR regardless of meaningful words.
    /// Normal English text has ~20-30% short words. 80%+ is definitive garbage.
    #[pyo3(get)]
    pub critical_fragmented_word_ratio: f64,
    /// Minimum average word length. Below this with enough words indicates garbled extraction.
    #[pyo3(get)]
    pub min_avg_word_length: f64,
    /// Minimum word count before average word length check applies.
    #[pyo3(get)]
    pub min_words_for_avg_length_check: usize,
    /// Minimum consecutive word repetition ratio to detect column scrambling.
    #[pyo3(get)]
    pub min_consecutive_repeat_ratio: f64,
    /// Minimum word count before consecutive repetition check is applied.
    #[pyo3(get)]
    pub min_words_for_repeat_check: usize,
    /// Minimum character count for "substantive markdown" OCR skip gate.
    #[pyo3(get)]
    pub substantive_min_chars: usize,
    /// Minimum character count for "non-text content" OCR skip gate.
    #[pyo3(get)]
    pub non_text_min_chars: usize,
    /// Alphanumeric+whitespace ratio threshold for skip decisions.
    #[pyo3(get)]
    pub alnum_ws_ratio_threshold: f64,
    /// Minimum quality score (0.0-1.0) for a pipeline stage result to be accepted.
    /// If the result from a backend scores below this, try the next backend.
    #[pyo3(get)]
    pub pipeline_min_quality: f64,
}

#[pymethods]
impl OcrQualityThresholds {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (min_total_non_whitespace=Self::default().min_total_non_whitespace, min_non_whitespace_per_page=Self::default().min_non_whitespace_per_page, min_meaningful_word_len=Self::default().min_meaningful_word_len, min_meaningful_words=Self::default().min_meaningful_words, min_alnum_ratio=Self::default().min_alnum_ratio, min_garbage_chars=Self::default().min_garbage_chars, max_fragmented_word_ratio=Self::default().max_fragmented_word_ratio, critical_fragmented_word_ratio=Self::default().critical_fragmented_word_ratio, min_avg_word_length=Self::default().min_avg_word_length, min_words_for_avg_length_check=Self::default().min_words_for_avg_length_check, min_consecutive_repeat_ratio=Self::default().min_consecutive_repeat_ratio, min_words_for_repeat_check=Self::default().min_words_for_repeat_check, substantive_min_chars=Self::default().substantive_min_chars, non_text_min_chars=Self::default().non_text_min_chars, alnum_ws_ratio_threshold=Self::default().alnum_ws_ratio_threshold, pipeline_min_quality=Self::default().pipeline_min_quality))]
    #[new]
    pub fn new(
        min_total_non_whitespace: usize,
        min_non_whitespace_per_page: f64,
        min_meaningful_word_len: usize,
        min_meaningful_words: usize,
        min_alnum_ratio: f64,
        min_garbage_chars: usize,
        max_fragmented_word_ratio: f64,
        critical_fragmented_word_ratio: f64,
        min_avg_word_length: f64,
        min_words_for_avg_length_check: usize,
        min_consecutive_repeat_ratio: f64,
        min_words_for_repeat_check: usize,
        substantive_min_chars: usize,
        non_text_min_chars: usize,
        alnum_ws_ratio_threshold: f64,
        pipeline_min_quality: f64,
    ) -> Self {
        Self {
            min_total_non_whitespace,
            min_non_whitespace_per_page,
            min_meaningful_word_len,
            min_meaningful_words,
            min_alnum_ratio,
            min_garbage_chars,
            max_fragmented_word_ratio,
            critical_fragmented_word_ratio,
            min_avg_word_length,
            min_words_for_avg_length_check,
            min_consecutive_repeat_ratio,
            min_words_for_repeat_check,
            substantive_min_chars,
            non_text_min_chars,
            alnum_ws_ratio_threshold,
            pipeline_min_quality,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> OcrQualityThresholds {
        kreuzberg::OcrQualityThresholds::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OcrPipelineStage {
    /// Backend name: "tesseract", "paddleocr", "easyocr", or a custom registered name.
    #[pyo3(get)]
    pub backend: String,
    /// Priority weight (higher = tried first). Stages are sorted by priority descending.
    #[pyo3(get)]
    pub priority: u32,
    /// Language override for this stage (None = use parent OcrConfig.language).
    #[pyo3(get)]
    pub language: Option<String>,
    /// Tesseract-specific config override for this stage.
    #[pyo3(get)]
    pub tesseract_config: Option<TesseractConfig>,
    /// PaddleOCR-specific config for this stage.
    #[pyo3(get)]
    #[serde(default, deserialize_with = "alef_json_str_opt::deserialize")]
    pub paddle_ocr_config: Option<String>,
    /// VLM config override for this pipeline stage.
    #[pyo3(get)]
    pub vlm_config: Option<LlmConfig>,
    /// Arbitrary per-call options passed through to the backend unchanged.
    ///
    /// Backends that support runtime tuning (mode switching, preprocessing
    /// flags, inference parameters, etc.) read this value and deserialize
    /// the keys they care about. Keys unknown to the backend are silently
    /// ignored, so options from different backends can coexist in the same
    /// config without conflict.
    ///
    /// Example (custom backend):
    /// ```json
    /// { "mode": "fast", "enable_layout": true }
    /// ```
    #[pyo3(get)]
    #[serde(default, deserialize_with = "alef_json_str_opt::deserialize")]
    pub backend_options: Option<String>,
}

#[pymethods]
impl OcrPipelineStage {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (backend, priority, language=None, tesseract_config=None, paddle_ocr_config=None, vlm_config=None, backend_options=None))]
    #[new]
    pub fn new(
        backend: String,
        priority: u32,
        language: Option<String>,
        tesseract_config: Option<TesseractConfig>,
        paddle_ocr_config: Option<String>,
        vlm_config: Option<LlmConfig>,
        backend_options: Option<String>,
    ) -> Self {
        Self {
            backend,
            priority,
            language,
            tesseract_config,
            paddle_ocr_config,
            vlm_config,
            backend_options,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OcrPipelineConfig {
    /// Ordered list of backends to try. Sorted by priority (descending) at runtime.
    #[pyo3(get)]
    pub stages: Vec<OcrPipelineStage>,
    /// Quality thresholds for deciding whether to accept a result or try the next backend.
    #[pyo3(get)]
    pub quality_thresholds: OcrQualityThresholds,
}

#[pymethods]
impl OcrPipelineConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (stages, quality_thresholds))]
    #[new]
    pub fn new(stages: Vec<OcrPipelineStage>, quality_thresholds: OcrQualityThresholds) -> Self {
        Self {
            stages,
            quality_thresholds,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OcrConfig {
    /// Whether OCR is enabled.
    ///
    /// Setting `enabled: false` is a shorthand for `disable_ocr: true` on the parent
    /// [`ExtractionConfig`](crate::core::config::ExtractionConfig). Images return
    /// metadata only; PDFs use native text extraction without OCR fallback.
    ///
    /// Defaults to `true`. When `false`, all other OCR settings are ignored.
    #[pyo3(get)]
    pub enabled: bool,
    /// OCR backend: tesseract, easyocr, paddleocr
    #[pyo3(get)]
    pub backend: String,
    /// Language code (e.g., "eng", "deu")
    #[pyo3(get)]
    pub language: String,
    /// Tesseract-specific configuration (optional)
    #[pyo3(get)]
    pub tesseract_config: Option<TesseractConfig>,
    /// Output format for OCR results (optional, for format conversion)
    #[pyo3(get)]
    pub output_format: Option<OutputFormat>,
    /// PaddleOCR-specific configuration (optional, JSON passthrough)
    #[pyo3(get)]
    #[serde(default, deserialize_with = "alef_json_str_opt::deserialize")]
    pub paddle_ocr_config: Option<String>,
    /// Arbitrary per-call options passed through to the backend unchanged.
    ///
    /// Custom OCR backends and built-in backends that support runtime tuning
    /// can read this value and deserialize the keys they care about. Keys
    /// unknown to the backend are silently ignored.
    ///
    /// This is the recommended extension point for per-call parameters that
    /// are not covered by the typed fields above (e.g. mode switching,
    /// preprocessing flags, inference batch size).
    ///
    /// **Scope:** when `pipeline` is `None`, this value is propagated to the
    /// primary stage of the auto-constructed pipeline. When `pipeline` is
    /// explicitly set, this field has **no effect** — the caller must set
    /// `OcrPipelineStage.backend_options` directly on the relevant stage(s)
    /// instead.
    ///
    /// Example:
    /// ```json
    /// { "mode": "fast", "enable_layout": true, "timeout_ms": 5000 }
    /// ```
    #[pyo3(get)]
    #[serde(default, deserialize_with = "alef_json_str_opt::deserialize")]
    pub backend_options: Option<String>,
    /// OCR element extraction configuration
    #[pyo3(get)]
    pub element_config: Option<OcrElementConfig>,
    /// Quality thresholds for the native-text-to-OCR fallback decision.
    /// When None, uses compiled defaults (matching previous hardcoded behavior).
    #[pyo3(get)]
    pub quality_thresholds: Option<OcrQualityThresholds>,
    /// Multi-backend OCR pipeline configuration. When set, enables weighted
    /// fallback across multiple OCR backends based on output quality.
    /// When None, uses the single `backend` field (same as today).
    #[pyo3(get)]
    pub pipeline: Option<OcrPipelineConfig>,
    /// Enable automatic page rotation based on orientation detection.
    ///
    /// When enabled, uses Tesseract's `DetectOrientationScript()` to detect
    /// page orientation (0/90/180/270 degrees) before OCR. If the page is
    /// rotated with high confidence, the image is corrected before recognition.
    /// This is critical for handling rotated scanned documents.
    #[pyo3(get)]
    pub auto_rotate: bool,
    /// VLM (Vision Language Model) OCR configuration.
    ///
    /// Required when `backend` is `"vlm"`. Uses liter-llm to send page
    /// images to a vision model for text extraction.
    #[pyo3(get)]
    pub vlm_config: Option<LlmConfig>,
    /// Custom Jinja2 prompt template for VLM OCR.
    ///
    /// When `None`, uses the default template. Available variables:
    /// - `{{ language }}` — The document language code (e.g., "eng", "deu").
    #[pyo3(get)]
    pub vlm_prompt: Option<String>,
    /// Hardware acceleration for ONNX Runtime models (e.g. PaddleOCR, layout detection).
    ///
    /// Not user-configurable via config files — injected at runtime from
    /// `ExtractionConfig::acceleration` before each `process_image` call.
    #[pyo3(get)]
    pub acceleration: Option<AccelerationConfig>,
    /// Caller-supplied Tesseract `traineddata` bytes per language code.
    ///
    /// Primary use case is the WASM build, which has no filesystem and cannot
    /// download tessdata at runtime. Native builds typically rely on
    /// `TessdataManager` and ignore this field. When present, the WASM
    /// Tesseract backend prefers these bytes over its compile-time-bundled
    /// English data.
    ///
    /// Skipped by serde to keep config files small — supply via the typed API
    /// at runtime.
    #[pyo3(get)]
    pub tessdata_bytes: Option<HashMap<String, Vec<u8>>>,
}

#[pymethods]
impl OcrConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (enabled=Self::default().enabled, backend=Self::default().backend, language=Self::default().language, auto_rotate=Self::default().auto_rotate, tesseract_config=None, output_format=None, paddle_ocr_config=None, backend_options=None, element_config=None, quality_thresholds=None, pipeline=None, vlm_config=None, vlm_prompt=None, acceleration=None, tessdata_bytes=None))]
    #[new]
    pub fn new(
        enabled: bool,
        backend: String,
        language: String,
        auto_rotate: bool,
        tesseract_config: Option<TesseractConfig>,
        output_format: Option<OutputFormat>,
        paddle_ocr_config: Option<String>,
        backend_options: Option<String>,
        element_config: Option<OcrElementConfig>,
        quality_thresholds: Option<OcrQualityThresholds>,
        pipeline: Option<OcrPipelineConfig>,
        vlm_config: Option<LlmConfig>,
        vlm_prompt: Option<String>,
        acceleration: Option<AccelerationConfig>,
        tessdata_bytes: Option<HashMap<String, Vec<u8>>>,
    ) -> Self {
        Self {
            enabled,
            backend,
            language,
            tesseract_config,
            output_format,
            paddle_ocr_config,
            backend_options,
            element_config,
            quality_thresholds,
            pipeline,
            auto_rotate,
            vlm_config,
            vlm_prompt,
            acceleration,
            tessdata_bytes,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> OcrConfig {
        kreuzberg::OcrConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PageConfig {
    /// Extract pages as separate array (ExtractionResult.pages)
    #[pyo3(get)]
    pub extract_pages: bool,
    /// Insert page markers in main content string
    #[pyo3(get)]
    pub insert_page_markers: bool,
    /// Page marker format (use {page_num} placeholder)
    /// Default: "\n\n<!-- PAGE {page_num} -->\n\n"
    #[pyo3(get)]
    pub marker_format: String,
}

#[pymethods]
impl PageConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (extract_pages=Self::default().extract_pages, insert_page_markers=Self::default().insert_page_markers, marker_format=Self::default().marker_format))]
    #[new]
    pub fn new(extract_pages: bool, insert_page_markers: bool, marker_format: String) -> Self {
        Self {
            extract_pages,
            insert_page_markers,
            marker_format,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> PageConfig {
        kreuzberg::PageConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PdfConfig {
    /// Extract images from PDF
    #[pyo3(get)]
    pub extract_images: bool,
    /// Extract tables from PDF.
    ///
    /// When `true` (default), runs pdf_oxide's native grid detector and, if it
    /// finds nothing, falls back to the heuristic text-layer reconstruction in
    /// `pdf::oxide::table::extract_tables_heuristic`. Set to `false` to skip
    /// both passes — `tables` will then be empty in the result.
    #[pyo3(get)]
    pub extract_tables: bool,
    /// List of passwords to try when opening encrypted PDFs
    #[pyo3(get)]
    pub passwords: Option<Vec<String>>,
    /// Extract PDF metadata
    #[pyo3(get)]
    pub extract_metadata: bool,
    /// Hierarchy extraction configuration (None = hierarchy extraction disabled)
    #[pyo3(get)]
    pub hierarchy: Option<HierarchyConfig>,
    /// Extract PDF annotations (text notes, highlights, links, stamps).
    /// Default: false
    #[pyo3(get)]
    pub extract_annotations: bool,
    /// Top margin fraction (0.0–1.0) of page height to exclude headers/running heads.
    /// Default: 0.06 (6%)
    #[pyo3(get)]
    pub top_margin_fraction: Option<f32>,
    /// Bottom margin fraction (0.0–1.0) of page height to exclude footers/page numbers.
    /// Default: 0.05 (5%)
    #[pyo3(get)]
    pub bottom_margin_fraction: Option<f32>,
    /// Allow single-column pseudo tables in extraction results.
    ///
    /// By default, tables with fewer than 2 columns (layout-guided) or 3 columns
    /// (heuristic) are rejected. When `true`, the minimum column count is relaxed
    /// to 1, allowing single-column structured data (glossaries, itemized lists)
    /// to be emitted as tables. Other quality filters (density, sparsity, prose
    /// detection) still apply.
    #[pyo3(get)]
    pub allow_single_column_tables: bool,
    /// Perform OCR on inline images extracted from PDF pages and attach the
    /// recognized text to each `ExtractedImage.ocr_result`. Requires Tesseract
    /// to be available; if `ExtractionConfig.ocr` is `None` the extractor
    /// falls back to `TesseractConfig::default()`. Per-image failures degrade
    /// gracefully (the image is returned without OCR text rather than failing
    /// the whole extraction). Default: `false`.
    #[pyo3(get)]
    pub ocr_inline_images: bool,
}

#[pymethods]
impl PdfConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (extract_images=Self::default().extract_images, extract_tables=Self::default().extract_tables, extract_metadata=Self::default().extract_metadata, extract_annotations=Self::default().extract_annotations, allow_single_column_tables=Self::default().allow_single_column_tables, ocr_inline_images=Self::default().ocr_inline_images, passwords=None, hierarchy=None, top_margin_fraction=None, bottom_margin_fraction=None))]
    #[new]
    pub fn new(
        extract_images: bool,
        extract_tables: bool,
        extract_metadata: bool,
        extract_annotations: bool,
        allow_single_column_tables: bool,
        ocr_inline_images: bool,
        passwords: Option<Vec<String>>,
        hierarchy: Option<HierarchyConfig>,
        top_margin_fraction: Option<f32>,
        bottom_margin_fraction: Option<f32>,
    ) -> Self {
        Self {
            extract_images,
            extract_tables,
            passwords,
            extract_metadata,
            hierarchy,
            extract_annotations,
            top_margin_fraction,
            bottom_margin_fraction,
            allow_single_column_tables,
            ocr_inline_images,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> PdfConfig {
        kreuzberg::PdfConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct HierarchyConfig {
    /// Enable hierarchy extraction
    #[pyo3(get)]
    pub enabled: bool,
    /// Number of font size clusters to use for hierarchy levels (1-7)
    ///
    /// Default: 6, which provides H1-H6 heading levels with body text.
    /// Larger values create more fine-grained hierarchy levels.
    #[pyo3(get)]
    pub k_clusters: usize,
    /// Include bounding box information in hierarchy blocks
    #[pyo3(get)]
    pub include_bbox: bool,
    /// OCR coverage threshold for smart OCR triggering (0.0-1.0)
    ///
    /// Determines when OCR should be triggered based on text block coverage.
    /// OCR is triggered when text blocks cover less than this fraction of the page.
    /// Default: 0.5 (trigger OCR if less than 50% of page has text)
    #[pyo3(get)]
    pub ocr_coverage_threshold: Option<f32>,
}

#[pymethods]
impl HierarchyConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (enabled=Self::default().enabled, k_clusters=Self::default().k_clusters, include_bbox=Self::default().include_bbox, ocr_coverage_threshold=None))]
    #[new]
    pub fn new(enabled: bool, k_clusters: usize, include_bbox: bool, ocr_coverage_threshold: Option<f32>) -> Self {
        Self {
            enabled,
            k_clusters,
            include_bbox,
            ocr_coverage_threshold,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> HierarchyConfig {
        kreuzberg::HierarchyConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PostProcessorConfig {
    /// Enable post-processors
    #[pyo3(get)]
    pub enabled: bool,
    /// Whitelist of processor names to run (None = all enabled)
    #[pyo3(get)]
    pub enabled_processors: Option<Vec<String>>,
    /// Blacklist of processor names to skip (None = none disabled)
    #[pyo3(get)]
    pub disabled_processors: Option<Vec<String>>,
    /// Pre-computed AHashSet for O(1) enabled processor lookup
    #[pyo3(get)]
    pub enabled_set: Option<Vec<String>>,
    /// Pre-computed AHashSet for O(1) disabled processor lookup
    #[pyo3(get)]
    pub disabled_set: Option<Vec<String>>,
}

#[pymethods]
impl PostProcessorConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (enabled=Self::default().enabled, enabled_processors=None, disabled_processors=None, enabled_set=None, disabled_set=None))]
    #[new]
    pub fn new(
        enabled: bool,
        enabled_processors: Option<Vec<String>>,
        disabled_processors: Option<Vec<String>>,
        enabled_set: Option<Vec<String>>,
        disabled_set: Option<Vec<String>>,
    ) -> Self {
        Self {
            enabled,
            enabled_processors,
            disabled_processors,
            enabled_set,
            disabled_set,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> PostProcessorConfig {
        kreuzberg::PostProcessorConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ChunkingConfig {
    /// Maximum size per chunk (in units determined by `sizing`).
    ///
    /// When `sizing` is `Characters` (default), this is the max character count.
    /// When using token-based sizing, this is the max token count.
    ///
    /// Default: 1000
    #[pyo3(get)]
    #[serde(rename = "max_chars")]
    pub max_characters: usize,
    /// Overlap between chunks (in units determined by `sizing`).
    ///
    /// Default: 200
    #[pyo3(get)]
    #[serde(rename = "max_overlap")]
    pub overlap: usize,
    /// Whether to trim whitespace from chunk boundaries.
    ///
    /// Default: true
    #[pyo3(get)]
    pub trim: bool,
    /// Type of chunker to use (Text or Markdown).
    ///
    /// Default: Text
    #[pyo3(get)]
    pub chunker_type: ChunkerType,
    /// Optional embedding configuration for chunk embeddings.
    #[pyo3(get)]
    #[serde(skip)]
    pub embedding: Option<EmbeddingConfig>,
    /// Use a preset configuration (overrides individual settings if provided).
    #[pyo3(get)]
    pub preset: Option<String>,
    /// How to measure chunk size.
    ///
    /// Default: `Characters` (Unicode character count).
    /// Enable `chunking-tiktoken` or `chunking-tokenizers` features for token-based sizing.
    #[pyo3(get)]
    pub sizing: ChunkSizing,
    /// When `true` and `chunker_type` is `Markdown`, prepend the heading hierarchy
    /// path (e.g. `"# Title > ## Section\n\n"`) to each chunk's content string.
    ///
    /// This is useful for RAG pipelines where each chunk needs self-contained
    /// context about its position in the document structure.
    ///
    /// Default: `false`
    #[pyo3(get)]
    pub prepend_heading_context: bool,
    /// Optional cosine similarity threshold for semantic topic boundary detection.
    ///
    /// Only used when `chunker_type` is `Semantic` and an `EmbeddingConfig` is
    /// provided. You almost never need to set this. When omitted, defaults to
    /// `0.75` which works well for most documents. Lower values detect more
    /// topic boundaries (more, smaller chunks); higher values detect fewer.
    /// Range: `0.0..=1.0`.
    #[pyo3(get)]
    pub topic_threshold: Option<f32>,
}

#[pymethods]
impl ChunkingConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (max_chars=Self::default().max_characters, max_overlap=Self::default().overlap, trim=Self::default().trim, chunker_type=Self::default().chunker_type, sizing=Self::default().sizing, prepend_heading_context=Self::default().prepend_heading_context, embedding=None, preset=None, topic_threshold=None))]
    #[new]
    pub fn new(
        max_chars: usize,
        max_overlap: usize,
        trim: bool,
        chunker_type: ChunkerType,
        sizing: ChunkSizing,
        prepend_heading_context: bool,
        embedding: Option<EmbeddingConfig>,
        preset: Option<String>,
        topic_threshold: Option<f32>,
    ) -> Self {
        Self {
            max_characters: max_chars,
            overlap: max_overlap,
            trim,
            chunker_type,
            embedding,
            preset,
            sizing,
            prepend_heading_context,
            topic_threshold,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> ChunkingConfig {
        kreuzberg::ChunkingConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct EmbeddingConfig {
    /// The embedding model to use (defaults to "balanced" preset if not specified)
    #[pyo3(get)]
    pub model: EmbeddingModelType,
    /// Whether to normalize embedding vectors (recommended for cosine similarity)
    #[pyo3(get)]
    pub normalize: bool,
    /// Batch size for embedding generation
    #[pyo3(get)]
    pub batch_size: usize,
    /// Show model download progress
    #[pyo3(get)]
    pub show_download_progress: bool,
    /// Custom cache directory for model files
    ///
    /// Defaults to `~/.cache/kreuzberg/embeddings/` if not specified.
    /// Allows full customization of model download location.
    #[pyo3(get)]
    pub cache_dir: Option<String>,
    /// Hardware acceleration for the embedding ONNX model.
    ///
    /// When set, controls which execution provider (CPU, CUDA, CoreML, TensorRT)
    /// is used for inference. Defaults to `None` (auto-select per platform).
    #[pyo3(get)]
    pub acceleration: Option<AccelerationConfig>,
    /// Maximum wall-clock duration (in seconds) for a single `embed()` call when
    /// using [`EmbeddingModelType::Plugin`].
    ///
    /// Applies only to the in-process plugin path — protects against hung
    /// host-language backends (e.g. a Python callback deadlocked on the GIL,
    /// a model stuck on CUDA OOM retries, etc.). On timeout, the dispatcher
    /// returns `Plugin` instead of blocking forever.
    ///
    /// `None` disables the timeout. The default (60 seconds) is conservative
    /// for common in-process inference; increase for large batches on slow
    /// hardware.
    #[pyo3(get)]
    pub max_embed_duration_secs: Option<u64>,
}

#[pymethods]
impl EmbeddingConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (model=Self::default().model, normalize=Self::default().normalize, batch_size=Self::default().batch_size, show_download_progress=Self::default().show_download_progress, cache_dir=None, acceleration=None, max_embed_duration_secs=None))]
    #[new]
    pub fn new(
        model: EmbeddingModelType,
        normalize: bool,
        batch_size: usize,
        show_download_progress: bool,
        cache_dir: Option<String>,
        acceleration: Option<AccelerationConfig>,
        max_embed_duration_secs: Option<u64>,
    ) -> Self {
        Self {
            model,
            normalize,
            batch_size,
            show_download_progress,
            cache_dir,
            acceleration,
            max_embed_duration_secs,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> EmbeddingConfig {
        kreuzberg::EmbeddingConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct TreeSitterConfig {
    /// Enable code intelligence processing (default: true).
    ///
    /// When `false`, tree-sitter analysis is completely skipped even if
    /// the config section is present.
    #[pyo3(get)]
    pub enabled: bool,
    /// Custom cache directory for downloaded grammars.
    ///
    /// When `None`, uses the default: `~/.cache/tree-sitter-language-pack/v{version}/libs/`.
    #[pyo3(get)]
    pub cache_dir: Option<String>,
    /// Languages to pre-download on init (e.g., `["python", "rust"]`).
    #[pyo3(get)]
    pub languages: Option<Vec<String>>,
    /// Language groups to pre-download (e.g., `["web", "systems", "scripting"]`).
    #[pyo3(get)]
    pub groups: Option<Vec<String>>,
    /// Processing options for code analysis.
    #[pyo3(get)]
    pub process: TreeSitterProcessConfig,
}

#[pymethods]
impl TreeSitterConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (enabled=Self::default().enabled, process=None, cache_dir=None, languages=None, groups=None))]
    #[new]
    pub fn new(
        enabled: bool,
        process: Option<TreeSitterProcessConfig>,
        cache_dir: Option<String>,
        languages: Option<Vec<String>>,
        groups: Option<Vec<String>>,
    ) -> Self {
        Self {
            enabled,
            cache_dir,
            languages,
            groups,
            process: process.unwrap_or_else(|| Self::default().process),
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> TreeSitterConfig {
        kreuzberg::TreeSitterConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct TreeSitterProcessConfig {
    /// Extract structural items (functions, classes, structs, etc.). Default: true.
    #[pyo3(get)]
    pub structure: bool,
    /// Extract import statements. Default: true.
    #[pyo3(get)]
    pub imports: bool,
    /// Extract export statements. Default: true.
    #[pyo3(get)]
    pub exports: bool,
    /// Extract comments. Default: false.
    #[pyo3(get)]
    pub comments: bool,
    /// Extract docstrings. Default: false.
    #[pyo3(get)]
    pub docstrings: bool,
    /// Extract symbol definitions. Default: false.
    #[pyo3(get)]
    pub symbols: bool,
    /// Include parse diagnostics. Default: false.
    #[pyo3(get)]
    pub diagnostics: bool,
    /// Maximum chunk size in bytes. `None` disables chunking.
    #[pyo3(get)]
    pub chunk_max_size: Option<usize>,
    /// Content rendering mode for code extraction.
    #[pyo3(get)]
    pub content_mode: CodeContentMode,
}

#[pymethods]
impl TreeSitterProcessConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (structure=Self::default().structure, imports=Self::default().imports, exports=Self::default().exports, comments=Self::default().comments, docstrings=Self::default().docstrings, symbols=Self::default().symbols, diagnostics=Self::default().diagnostics, content_mode=Self::default().content_mode, chunk_max_size=None))]
    #[new]
    pub fn new(
        structure: bool,
        imports: bool,
        exports: bool,
        comments: bool,
        docstrings: bool,
        symbols: bool,
        diagnostics: bool,
        content_mode: CodeContentMode,
        chunk_max_size: Option<usize>,
    ) -> Self {
        Self {
            structure,
            imports,
            exports,
            comments,
            docstrings,
            symbols,
            diagnostics,
            chunk_max_size,
            content_mode,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> TreeSitterProcessConfig {
        kreuzberg::TreeSitterProcessConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct SupportedFormat {
    /// File extension (without leading dot), e.g., "pdf", "docx"
    #[pyo3(get)]
    pub extension: String,
    /// MIME type string, e.g., "application/pdf"
    #[pyo3(get)]
    pub mime_type: String,
}

#[pymethods]
impl SupportedFormat {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (extension, mime_type))]
    #[new]
    pub fn new(extension: String, mime_type: String) -> Self {
        Self { extension, mime_type }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct ServerConfig {
    /// Server host address (e.g., "127.0.0.1", "0.0.0.0")
    #[pyo3(get)]
    pub host: String,
    /// Server port number
    #[pyo3(get)]
    pub port: u16,
    /// CORS allowed origins. Empty vector means allow all origins.
    ///
    /// If this is an empty vector, the server will accept requests from any origin.
    /// If populated with specific origins (e.g., `"https://example.com"`), only
    /// those origins will be allowed.
    #[pyo3(get)]
    pub cors_origins: Vec<String>,
    /// Maximum size of request body in bytes (default: 100 MB)
    #[pyo3(get)]
    pub max_request_body_bytes: usize,
    /// Maximum size of multipart fields in bytes (default: 100 MB)
    #[pyo3(get)]
    pub max_multipart_field_bytes: usize,
}

#[pymethods]
impl ServerConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (host=Self::default().host, port=Self::default().port, cors_origins=Self::default().cors_origins, max_request_body_bytes=Self::default().max_request_body_bytes, max_multipart_field_bytes=Self::default().max_multipart_field_bytes))]
    #[new]
    pub fn new(
        host: String,
        port: u16,
        cors_origins: Vec<String>,
        max_request_body_bytes: usize,
        max_multipart_field_bytes: usize,
    ) -> Self {
        Self {
            host,
            port,
            cors_origins,
            max_request_body_bytes,
            max_multipart_field_bytes,
        }
    }

    #[pyo3(signature = ())]
    pub fn listen_addr(&self) -> String {
        let core_self = kreuzberg::ServerConfig {
            host: self.host.clone(),

            port: self.port,

            cors_origins: self.cors_origins.clone(),

            max_request_body_bytes: self.max_request_body_bytes,

            max_multipart_field_bytes: self.max_multipart_field_bytes,
        };
        core_self.listen_addr()
    }

    #[pyo3(signature = ())]
    pub fn cors_allows_all(&self) -> bool {
        let core_self = kreuzberg::ServerConfig {
            host: self.host.clone(),

            port: self.port,

            cors_origins: self.cors_origins.clone(),

            max_request_body_bytes: self.max_request_body_bytes,

            max_multipart_field_bytes: self.max_multipart_field_bytes,
        };
        core_self.cors_allows_all()
    }

    #[pyo3(signature = (origin))]
    pub fn is_origin_allowed(&self, origin: String) -> bool {
        let core_self = kreuzberg::ServerConfig {
            host: self.host.clone(),

            port: self.port,

            cors_origins: self.cors_origins.clone(),

            max_request_body_bytes: self.max_request_body_bytes,

            max_multipart_field_bytes: self.max_multipart_field_bytes,
        };
        core_self.is_origin_allowed(&origin)
    }

    #[pyo3(signature = ())]
    pub fn max_request_body_mb(&self) -> usize {
        let core_self = kreuzberg::ServerConfig {
            host: self.host.clone(),

            port: self.port,

            cors_origins: self.cors_origins.clone(),

            max_request_body_bytes: self.max_request_body_bytes,

            max_multipart_field_bytes: self.max_multipart_field_bytes,
        };
        core_self.max_request_body_mb()
    }

    #[pyo3(signature = ())]
    pub fn max_multipart_field_mb(&self) -> usize {
        let core_self = kreuzberg::ServerConfig {
            host: self.host.clone(),

            port: self.port,

            cors_origins: self.cors_origins.clone(),

            max_request_body_bytes: self.max_request_body_bytes,

            max_multipart_field_bytes: self.max_multipart_field_bytes,
        };
        core_self.max_multipart_field_mb()
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> ServerConfig {
        kreuzberg::ServerConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct StructuredDataResult {
    #[pyo3(get)]
    pub content: String,
    #[pyo3(get)]
    pub format: String,
    #[pyo3(get)]
    pub metadata: HashMap<String, String>,
    #[pyo3(get)]
    pub text_fields: Vec<String>,
}

#[pymethods]
impl StructuredDataResult {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content, format, metadata, text_fields))]
    #[new]
    pub fn new(content: String, format: String, metadata: HashMap<String, String>, text_fields: Vec<String>) -> Self {
        Self {
            content,
            format,
            metadata,
            text_fields,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DocxAppProperties {
    /// Application name (e.g., "Microsoft Office Word")
    #[pyo3(get)]
    pub application: Option<String>,
    /// Application version
    #[pyo3(get)]
    pub app_version: Option<String>,
    /// Template filename
    #[pyo3(get)]
    pub template: Option<String>,
    /// Total editing time in minutes
    #[pyo3(get)]
    pub total_time: Option<i32>,
    /// Number of pages
    #[pyo3(get)]
    pub pages: Option<i32>,
    /// Number of words
    #[pyo3(get)]
    pub words: Option<i32>,
    /// Number of characters (excluding spaces)
    #[pyo3(get)]
    pub characters: Option<i32>,
    /// Number of characters (including spaces)
    #[pyo3(get)]
    pub characters_with_spaces: Option<i32>,
    /// Number of lines
    #[pyo3(get)]
    pub lines: Option<i32>,
    /// Number of paragraphs
    #[pyo3(get)]
    pub paragraphs: Option<i32>,
    /// Company name
    #[pyo3(get)]
    pub company: Option<String>,
    /// Document security level
    #[pyo3(get)]
    pub doc_security: Option<i32>,
    /// Scale crop flag
    #[pyo3(get)]
    pub scale_crop: Option<bool>,
    /// Links up to date flag
    #[pyo3(get)]
    pub links_up_to_date: Option<bool>,
    /// Shared document flag
    #[pyo3(get)]
    pub shared_doc: Option<bool>,
    /// Hyperlinks changed flag
    #[pyo3(get)]
    pub hyperlinks_changed: Option<bool>,
}

#[pymethods]
impl DocxAppProperties {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (application=None, app_version=None, template=None, total_time=None, pages=None, words=None, characters=None, characters_with_spaces=None, lines=None, paragraphs=None, company=None, doc_security=None, scale_crop=None, links_up_to_date=None, shared_doc=None, hyperlinks_changed=None))]
    #[new]
    pub fn new(
        application: Option<String>,
        app_version: Option<String>,
        template: Option<String>,
        total_time: Option<i32>,
        pages: Option<i32>,
        words: Option<i32>,
        characters: Option<i32>,
        characters_with_spaces: Option<i32>,
        lines: Option<i32>,
        paragraphs: Option<i32>,
        company: Option<String>,
        doc_security: Option<i32>,
        scale_crop: Option<bool>,
        links_up_to_date: Option<bool>,
        shared_doc: Option<bool>,
        hyperlinks_changed: Option<bool>,
    ) -> Self {
        Self {
            application,
            app_version,
            template,
            total_time,
            pages,
            words,
            characters,
            characters_with_spaces,
            lines,
            paragraphs,
            company,
            doc_security,
            scale_crop,
            links_up_to_date,
            shared_doc,
            hyperlinks_changed,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct XlsxAppProperties {
    /// Application name (e.g., "Microsoft Excel")
    #[pyo3(get)]
    pub application: Option<String>,
    /// Application version
    #[pyo3(get)]
    pub app_version: Option<String>,
    /// Document security level
    #[pyo3(get)]
    pub doc_security: Option<i32>,
    /// Scale crop flag
    #[pyo3(get)]
    pub scale_crop: Option<bool>,
    /// Links up to date flag
    #[pyo3(get)]
    pub links_up_to_date: Option<bool>,
    /// Shared document flag
    #[pyo3(get)]
    pub shared_doc: Option<bool>,
    /// Hyperlinks changed flag
    #[pyo3(get)]
    pub hyperlinks_changed: Option<bool>,
    /// Company name
    #[pyo3(get)]
    pub company: Option<String>,
    /// Worksheet names
    #[pyo3(get)]
    pub worksheet_names: Vec<String>,
}

#[pymethods]
impl XlsxAppProperties {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (worksheet_names=Self::default().worksheet_names, application=None, app_version=None, doc_security=None, scale_crop=None, links_up_to_date=None, shared_doc=None, hyperlinks_changed=None, company=None))]
    #[new]
    pub fn new(
        worksheet_names: Vec<String>,
        application: Option<String>,
        app_version: Option<String>,
        doc_security: Option<i32>,
        scale_crop: Option<bool>,
        links_up_to_date: Option<bool>,
        shared_doc: Option<bool>,
        hyperlinks_changed: Option<bool>,
        company: Option<String>,
    ) -> Self {
        Self {
            application,
            app_version,
            doc_security,
            scale_crop,
            links_up_to_date,
            shared_doc,
            hyperlinks_changed,
            company,
            worksheet_names,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PptxAppProperties {
    /// Application name (e.g., "Microsoft Office PowerPoint")
    #[pyo3(get)]
    pub application: Option<String>,
    /// Application version
    #[pyo3(get)]
    pub app_version: Option<String>,
    /// Total editing time in minutes
    #[pyo3(get)]
    pub total_time: Option<i32>,
    /// Company name
    #[pyo3(get)]
    pub company: Option<String>,
    /// Document security level
    #[pyo3(get)]
    pub doc_security: Option<i32>,
    /// Scale crop flag
    #[pyo3(get)]
    pub scale_crop: Option<bool>,
    /// Links up to date flag
    #[pyo3(get)]
    pub links_up_to_date: Option<bool>,
    /// Shared document flag
    #[pyo3(get)]
    pub shared_doc: Option<bool>,
    /// Hyperlinks changed flag
    #[pyo3(get)]
    pub hyperlinks_changed: Option<bool>,
    /// Number of slides
    #[pyo3(get)]
    pub slides: Option<i32>,
    /// Number of notes
    #[pyo3(get)]
    pub notes: Option<i32>,
    /// Number of hidden slides
    #[pyo3(get)]
    pub hidden_slides: Option<i32>,
    /// Number of multimedia clips
    #[pyo3(get)]
    pub multimedia_clips: Option<i32>,
    /// Presentation format (e.g., "Widescreen", "Standard")
    #[pyo3(get)]
    pub presentation_format: Option<String>,
    /// Slide titles
    #[pyo3(get)]
    pub slide_titles: Vec<String>,
}

#[pymethods]
impl PptxAppProperties {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (slide_titles=Self::default().slide_titles, application=None, app_version=None, total_time=None, company=None, doc_security=None, scale_crop=None, links_up_to_date=None, shared_doc=None, hyperlinks_changed=None, slides=None, notes=None, hidden_slides=None, multimedia_clips=None, presentation_format=None))]
    #[new]
    pub fn new(
        slide_titles: Vec<String>,
        application: Option<String>,
        app_version: Option<String>,
        total_time: Option<i32>,
        company: Option<String>,
        doc_security: Option<i32>,
        scale_crop: Option<bool>,
        links_up_to_date: Option<bool>,
        shared_doc: Option<bool>,
        hyperlinks_changed: Option<bool>,
        slides: Option<i32>,
        notes: Option<i32>,
        hidden_slides: Option<i32>,
        multimedia_clips: Option<i32>,
        presentation_format: Option<String>,
    ) -> Self {
        Self {
            application,
            app_version,
            total_time,
            company,
            doc_security,
            scale_crop,
            links_up_to_date,
            shared_doc,
            hyperlinks_changed,
            slides,
            notes,
            hidden_slides,
            multimedia_clips,
            presentation_format,
            slide_titles,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct CoreProperties {
    /// Document title
    #[pyo3(get)]
    pub title: Option<String>,
    /// Document subject/topic
    #[pyo3(get)]
    pub subject: Option<String>,
    /// Document creator/author
    #[pyo3(get)]
    pub creator: Option<String>,
    /// Keywords or tags
    #[pyo3(get)]
    pub keywords: Option<String>,
    /// Document description/abstract
    #[pyo3(get)]
    pub description: Option<String>,
    /// User who last modified the document
    #[pyo3(get)]
    pub last_modified_by: Option<String>,
    /// Revision number
    #[pyo3(get)]
    pub revision: Option<String>,
    /// Creation timestamp (ISO 8601)
    #[pyo3(get)]
    pub created: Option<String>,
    /// Last modification timestamp (ISO 8601)
    #[pyo3(get)]
    pub modified: Option<String>,
    /// Document category
    #[pyo3(get)]
    pub category: Option<String>,
    /// Content status (Draft, Final, etc.)
    #[pyo3(get)]
    pub content_status: Option<String>,
    /// Document language
    #[pyo3(get)]
    pub language: Option<String>,
    /// Unique identifier
    #[pyo3(get)]
    pub identifier: Option<String>,
    /// Document version
    #[pyo3(get)]
    pub version: Option<String>,
    /// Last print timestamp (ISO 8601)
    #[pyo3(get)]
    pub last_printed: Option<String>,
}

#[pymethods]
impl CoreProperties {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (title=None, subject=None, creator=None, keywords=None, description=None, last_modified_by=None, revision=None, created=None, modified=None, category=None, content_status=None, language=None, identifier=None, version=None, last_printed=None))]
    #[new]
    pub fn new(
        title: Option<String>,
        subject: Option<String>,
        creator: Option<String>,
        keywords: Option<String>,
        description: Option<String>,
        last_modified_by: Option<String>,
        revision: Option<String>,
        created: Option<String>,
        modified: Option<String>,
        category: Option<String>,
        content_status: Option<String>,
        language: Option<String>,
        identifier: Option<String>,
        version: Option<String>,
        last_printed: Option<String>,
    ) -> Self {
        Self {
            title,
            subject,
            creator,
            keywords,
            description,
            last_modified_by,
            revision,
            created,
            modified,
            category,
            content_status,
            language,
            identifier,
            version,
            last_printed,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct SecurityLimits {
    /// Maximum uncompressed size for archives (500 MB)
    #[pyo3(get)]
    pub max_archive_size: usize,
    /// Maximum compression ratio before flagging as potential bomb (100:1)
    #[pyo3(get)]
    pub max_compression_ratio: usize,
    /// Maximum number of files in archive (10,000)
    #[pyo3(get)]
    pub max_files_in_archive: usize,
    /// Maximum nesting depth for structures (100)
    #[pyo3(get)]
    pub max_nesting_depth: usize,
    /// Maximum length of any single XML entity / attribute / token (1 MiB).
    /// This is a per-token cap, NOT a total cap — billion-laughs class
    /// attacks where a single entity expands to hundreds of MB are caught
    /// here, while normal long text content (a paragraph, a CDATA block) is
    /// caught by `max_content_size` instead.
    #[pyo3(get)]
    pub max_entity_length: usize,
    /// Maximum string growth per document (100 MB)
    #[pyo3(get)]
    pub max_content_size: usize,
    /// Maximum iterations per operation
    #[pyo3(get)]
    pub max_iterations: usize,
    /// Maximum XML depth (100 levels)
    #[pyo3(get)]
    pub max_xml_depth: usize,
    /// Maximum cells per table (100,000)
    #[pyo3(get)]
    pub max_table_cells: usize,
}

#[pymethods]
impl SecurityLimits {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (max_archive_size=Self::default().max_archive_size, max_compression_ratio=Self::default().max_compression_ratio, max_files_in_archive=Self::default().max_files_in_archive, max_nesting_depth=Self::default().max_nesting_depth, max_entity_length=Self::default().max_entity_length, max_content_size=Self::default().max_content_size, max_iterations=Self::default().max_iterations, max_xml_depth=Self::default().max_xml_depth, max_table_cells=Self::default().max_table_cells))]
    #[new]
    pub fn new(
        max_archive_size: usize,
        max_compression_ratio: usize,
        max_files_in_archive: usize,
        max_nesting_depth: usize,
        max_entity_length: usize,
        max_content_size: usize,
        max_iterations: usize,
        max_xml_depth: usize,
        max_table_cells: usize,
    ) -> Self {
        Self {
            max_archive_size,
            max_compression_ratio,
            max_files_in_archive,
            max_nesting_depth,
            max_entity_length,
            max_content_size,
            max_iterations,
            max_xml_depth,
            max_table_cells,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> SecurityLimits {
        kreuzberg::SecurityLimits::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct TokenReductionConfig {
    #[pyo3(get)]
    pub level: ReductionLevel,
    #[pyo3(get)]
    pub language_hint: Option<String>,
    #[pyo3(get)]
    pub preserve_markdown: bool,
    #[pyo3(get)]
    pub preserve_code: bool,
    #[pyo3(get)]
    pub semantic_threshold: f32,
    #[pyo3(get)]
    pub enable_parallel: bool,
    #[pyo3(get)]
    pub use_simd: bool,
    #[pyo3(get)]
    pub custom_stopwords: Option<HashMap<String, Vec<String>>>,
    #[pyo3(get)]
    pub preserve_patterns: Vec<String>,
    #[pyo3(get)]
    pub target_reduction: Option<f32>,
    #[pyo3(get)]
    pub enable_semantic_clustering: bool,
}

#[pymethods]
impl TokenReductionConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (level=Self::default().level, preserve_markdown=Self::default().preserve_markdown, preserve_code=Self::default().preserve_code, semantic_threshold=Self::default().semantic_threshold, enable_parallel=Self::default().enable_parallel, use_simd=Self::default().use_simd, preserve_patterns=Self::default().preserve_patterns, enable_semantic_clustering=Self::default().enable_semantic_clustering, language_hint=None, custom_stopwords=None, target_reduction=None))]
    #[new]
    pub fn new(
        level: ReductionLevel,
        preserve_markdown: bool,
        preserve_code: bool,
        semantic_threshold: f32,
        enable_parallel: bool,
        use_simd: bool,
        preserve_patterns: Vec<String>,
        enable_semantic_clustering: bool,
        language_hint: Option<String>,
        custom_stopwords: Option<HashMap<String, Vec<String>>>,
        target_reduction: Option<f32>,
    ) -> Self {
        Self {
            level,
            language_hint,
            preserve_markdown,
            preserve_code,
            semantic_threshold,
            enable_parallel,
            use_simd,
            custom_stopwords,
            preserve_patterns,
            target_reduction,
            enable_semantic_clustering,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> TokenReductionConfig {
        kreuzberg::TokenReductionConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PdfAnnotation {
    /// The type of annotation.
    #[pyo3(get)]
    pub annotation_type: PdfAnnotationType,
    /// Text content of the annotation (e.g., comment text, link URL).
    #[pyo3(get)]
    pub content: Option<String>,
    /// Page number where the annotation appears (1-indexed).
    #[pyo3(get)]
    pub page_number: u32,
    /// Bounding box of the annotation on the page.
    #[pyo3(get)]
    pub bounding_box: Option<BoundingBox>,
}

#[pymethods]
impl PdfAnnotation {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (annotation_type, page_number, content=None, bounding_box=None))]
    #[new]
    pub fn new(
        annotation_type: PdfAnnotationType,
        page_number: u32,
        content: Option<String>,
        bounding_box: Option<BoundingBox>,
    ) -> Self {
        Self {
            annotation_type,
            content,
            page_number,
            bounding_box,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DjotContent {
    /// Plain text representation for backwards compatibility
    #[pyo3(get)]
    pub plain_text: String,
    /// Structured block-level content
    #[pyo3(get)]
    pub blocks: Vec<FormattedBlock>,
    /// Metadata from YAML frontmatter
    #[pyo3(get)]
    #[serde(skip)]
    pub metadata: Metadata,
    /// Extracted tables as structured data
    #[pyo3(get)]
    pub tables: Vec<Table>,
    /// Extracted images with metadata
    #[pyo3(get)]
    pub images: Vec<DjotImage>,
    /// Extracted links with URLs
    #[pyo3(get)]
    pub links: Vec<DjotLink>,
    /// Footnote definitions
    #[pyo3(get)]
    pub footnotes: Vec<Footnote>,
    /// Attributes mapped by element identifier (if present)
    #[pyo3(get)]
    #[serde(skip)]
    pub attributes: Vec<String>,
}

#[pymethods]
impl DjotContent {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (plain_text, blocks, metadata, tables, images, links, footnotes, attributes))]
    #[new]
    pub fn new(
        plain_text: String,
        blocks: Vec<FormattedBlock>,
        metadata: Metadata,
        tables: Vec<Table>,
        images: Vec<DjotImage>,
        links: Vec<DjotLink>,
        footnotes: Vec<Footnote>,
        attributes: Vec<String>,
    ) -> Self {
        Self {
            plain_text,
            blocks,
            metadata,
            tables,
            images,
            links,
            footnotes,
            attributes,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct FormattedBlock {
    /// Type of block element
    #[pyo3(get)]
    pub block_type: BlockType,
    /// Heading level (1-6) for headings, or nesting level for lists
    #[pyo3(get)]
    pub level: Option<usize>,
    /// Inline content within the block
    #[pyo3(get)]
    pub inline_content: Vec<InlineElement>,
    /// Element attributes (classes, IDs, key-value pairs)
    #[pyo3(get)]
    #[serde(skip)]
    pub attributes: Option<String>,
    /// Language identifier for code blocks
    #[pyo3(get)]
    pub language: Option<String>,
    /// Raw code content for code blocks
    #[pyo3(get)]
    pub code: Option<String>,
    /// Nested blocks for containers (blockquotes, list items, divs)
    #[pyo3(get)]
    pub children: Vec<FormattedBlock>,
}

#[pymethods]
impl FormattedBlock {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (block_type, inline_content, children, level=None, attributes=None, language=None, code=None))]
    #[new]
    pub fn new(
        block_type: BlockType,
        inline_content: Vec<InlineElement>,
        children: Vec<FormattedBlock>,
        level: Option<usize>,
        attributes: Option<String>,
        language: Option<String>,
        code: Option<String>,
    ) -> Self {
        Self {
            block_type,
            level,
            inline_content,
            attributes,
            language,
            code,
            children,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct InlineElement {
    /// Type of inline element
    #[pyo3(get)]
    pub element_type: InlineType,
    /// Text content
    #[pyo3(get)]
    pub content: String,
    /// Element attributes
    #[pyo3(get)]
    #[serde(skip)]
    pub attributes: Option<String>,
    /// Additional metadata (e.g., href for links, src/alt for images)
    #[pyo3(get)]
    pub metadata: Option<HashMap<String, String>>,
}

#[pymethods]
impl InlineElement {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (element_type, content, attributes=None, metadata=None))]
    #[new]
    pub fn new(
        element_type: InlineType,
        content: String,
        attributes: Option<String>,
        metadata: Option<HashMap<String, String>>,
    ) -> Self {
        Self {
            element_type,
            content,
            attributes,
            metadata,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DjotImage {
    /// Image source URL or path
    #[pyo3(get)]
    pub src: String,
    /// Alternative text
    #[pyo3(get)]
    pub alt: String,
    /// Optional title
    #[pyo3(get)]
    pub title: Option<String>,
    /// Element attributes
    #[pyo3(get)]
    #[serde(skip)]
    pub attributes: Option<String>,
}

#[pymethods]
impl DjotImage {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (src, alt, title=None, attributes=None))]
    #[new]
    pub fn new(src: String, alt: String, title: Option<String>, attributes: Option<String>) -> Self {
        Self {
            src,
            alt,
            title,
            attributes,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DjotLink {
    /// Link URL
    #[pyo3(get)]
    pub url: String,
    /// Link text content
    #[pyo3(get)]
    pub text: String,
    /// Optional title
    #[pyo3(get)]
    pub title: Option<String>,
    /// Element attributes
    #[pyo3(get)]
    #[serde(skip)]
    pub attributes: Option<String>,
}

#[pymethods]
impl DjotLink {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (url, text, title=None, attributes=None))]
    #[new]
    pub fn new(url: String, text: String, title: Option<String>, attributes: Option<String>) -> Self {
        Self {
            url,
            text,
            title,
            attributes,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct Footnote {
    /// Footnote label
    #[pyo3(get)]
    pub label: String,
    /// Footnote content blocks
    #[pyo3(get)]
    pub content: Vec<FormattedBlock>,
}

#[pymethods]
impl Footnote {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (label, content))]
    #[new]
    pub fn new(label: String, content: Vec<FormattedBlock>) -> Self {
        Self { label, content }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DocumentStructure {
    /// All nodes in document/reading order.
    #[pyo3(get)]
    #[serde(skip)]
    pub nodes: Vec<DocumentNode>,
    /// Origin format identifier (e.g. "docx", "pptx", "html", "pdf").
    ///
    /// Allows renderers to apply format-aware heuristics when converting
    /// the document tree to output formats.
    #[pyo3(get)]
    pub source_format: Option<String>,
    /// Resolved relationships between nodes (footnote refs, citations, anchor links, etc.).
    ///
    /// Populated during derivation from the internal document representation.
    /// Empty when no relationships are detected.
    #[pyo3(get)]
    pub relationships: Vec<DocumentRelationship>,
    /// Sorted, deduplicated list of node type names present in this document.
    ///
    /// Each value is the snake_case `node_type` tag of the corresponding
    /// [`NodeContent`] variant (e.g. `"paragraph"`, `"heading"`, `"table"`, …).
    ///
    /// Computed from [`nodes`] via [`DocumentStructure::finalize_node_types`].
    /// Empty until that method is called (internal construction paths call it
    /// at the end of derivation).
    #[pyo3(get)]
    pub node_types: Vec<String>,
}

#[pymethods]
impl DocumentStructure {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (nodes=Self::default().nodes, relationships=Self::default().relationships, node_types=Self::default().node_types, source_format=None))]
    #[new]
    pub fn new(
        nodes: Vec<DocumentNode>,
        relationships: Vec<DocumentRelationship>,
        node_types: Vec<String>,
        source_format: Option<String>,
    ) -> Self {
        Self {
            nodes,
            source_format,
            relationships,
            node_types,
        }
    }

    #[pyo3(signature = ())]
    pub fn finalize_node_types(&self) -> Self {
        let mut core_self = kreuzberg::DocumentStructure {
            nodes: self.nodes.clone().into_iter().map(Into::into).collect(),

            source_format: self.source_format.clone(),

            relationships: self.relationships.clone().into_iter().map(Into::into).collect(),

            node_types: self.node_types.clone(),
        };
        core_self.finalize_node_types();
        core_self.into()
    }

    #[pyo3(signature = ())]
    pub fn is_empty(&self) -> bool {
        let core_self = kreuzberg::DocumentStructure {
            nodes: self.nodes.clone().into_iter().map(Into::into).collect(),

            source_format: self.source_format.clone(),

            relationships: self.relationships.clone().into_iter().map(Into::into).collect(),

            node_types: self.node_types.clone(),
        };
        core_self.is_empty()
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> DocumentStructure {
        kreuzberg::DocumentStructure::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DocumentRelationship {
    /// Source node index (the referencing node).
    #[pyo3(get)]
    pub source: u32,
    /// Target node index (the referenced node).
    #[pyo3(get)]
    pub target: u32,
    /// Semantic kind of the relationship.
    #[pyo3(get)]
    pub kind: RelationshipKind,
}

#[pymethods]
impl DocumentRelationship {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (source, target, kind))]
    #[new]
    pub fn new(source: u32, target: u32, kind: RelationshipKind) -> Self {
        Self { source, target, kind }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DocumentNode {
    /// Deterministic identifier (hash of content + position).
    #[pyo3(get)]
    #[serde(skip)]
    pub id: String,
    /// Node content — tagged enum, type-specific data only.
    #[pyo3(get)]
    pub content: NodeContent,
    /// Parent node index (`None` = root-level node).
    #[pyo3(get)]
    pub parent: Option<u32>,
    /// Child node indices in reading order.
    #[pyo3(get)]
    pub children: Vec<u32>,
    /// Content layer classification.
    #[pyo3(get)]
    pub content_layer: ContentLayer,
    /// Page number where this node starts (1-indexed).
    #[pyo3(get)]
    pub page: Option<u32>,
    /// Page number where this node ends (for multi-page tables/sections).
    #[pyo3(get)]
    pub page_end: Option<u32>,
    /// Bounding box in document coordinates.
    #[pyo3(get)]
    pub bbox: Option<BoundingBox>,
    /// Inline annotations (formatting, links) on this node's text content.
    ///
    /// Only meaningful for text-carrying nodes; empty for containers.
    #[pyo3(get)]
    #[serde(skip)]
    pub annotations: Vec<TextAnnotation>,
    /// Format-specific key-value attributes.
    ///
    /// Extensible bag for miscellaneous data without a dedicated typed field: CSS classes,
    /// LaTeX environment names, Excel cell formulas, slide layout names, etc.
    #[pyo3(get)]
    pub attributes: Option<HashMap<String, String>>,
}

#[pymethods]
impl DocumentNode {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (id, content, children, content_layer, annotations, parent=None, page=None, page_end=None, bbox=None, attributes=None))]
    #[new]
    pub fn new(
        id: String,
        content: NodeContent,
        children: Vec<u32>,
        content_layer: ContentLayer,
        annotations: Vec<TextAnnotation>,
        parent: Option<u32>,
        page: Option<u32>,
        page_end: Option<u32>,
        bbox: Option<BoundingBox>,
        attributes: Option<HashMap<String, String>>,
    ) -> Self {
        Self {
            id,
            content,
            parent,
            children,
            content_layer,
            page,
            page_end,
            bbox,
            annotations,
            attributes,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct TableGrid {
    /// Number of rows in the table.
    #[pyo3(get)]
    pub rows: u32,
    /// Number of columns in the table.
    #[pyo3(get)]
    pub cols: u32,
    /// All cells in row-major order.
    #[pyo3(get)]
    pub cells: Vec<GridCell>,
}

#[pymethods]
impl TableGrid {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (rows=Self::default().rows, cols=Self::default().cols, cells=Self::default().cells))]
    #[new]
    pub fn new(rows: u32, cols: u32, cells: Vec<GridCell>) -> Self {
        Self { rows, cols, cells }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct GridCell {
    /// Cell text content.
    #[pyo3(get)]
    pub content: String,
    /// Zero-indexed row position.
    #[pyo3(get)]
    pub row: u32,
    /// Zero-indexed column position.
    #[pyo3(get)]
    pub col: u32,
    /// Number of rows this cell spans.
    #[pyo3(get)]
    pub row_span: u32,
    /// Number of columns this cell spans.
    #[pyo3(get)]
    pub col_span: u32,
    /// Whether this is a header cell.
    #[pyo3(get)]
    pub is_header: bool,
    /// Bounding box for this cell (if available).
    #[pyo3(get)]
    pub bbox: Option<BoundingBox>,
}

#[pymethods]
impl GridCell {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content, row, col, row_span, col_span, is_header, bbox=None))]
    #[new]
    pub fn new(
        content: String,
        row: u32,
        col: u32,
        row_span: u32,
        col_span: u32,
        is_header: bool,
        bbox: Option<BoundingBox>,
    ) -> Self {
        Self {
            content,
            row,
            col,
            row_span,
            col_span,
            is_header,
            bbox,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct TextAnnotation {
    /// Start byte offset in the node's text content (inclusive).
    #[pyo3(get)]
    pub start: u32,
    /// End byte offset in the node's text content (exclusive).
    #[pyo3(get)]
    pub end: u32,
    /// Annotation type.
    #[pyo3(get)]
    pub kind: AnnotationKind,
}

#[pymethods]
impl TextAnnotation {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (start, end, kind))]
    #[new]
    pub fn new(start: u32, end: u32, kind: AnnotationKind) -> Self {
        Self { start, end, kind }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ExtractionResult {
    #[pyo3(get)]
    pub content: String,
    #[pyo3(get)]
    pub mime_type: String,
    #[pyo3(get)]
    #[serde(skip)]
    pub metadata: Metadata,
    /// Extraction strategy used to produce the returned text.
    ///
    /// Populated when the extractor can reliably distinguish native text extraction,
    /// OCR-only extraction, or mixed native/OCR output.
    #[pyo3(get)]
    pub extraction_method: Option<ExtractionMethod>,
    #[pyo3(get)]
    pub tables: Vec<Table>,
    #[pyo3(get)]
    pub detected_languages: Option<Vec<String>>,
    /// Text chunks when chunking is enabled.
    ///
    /// When chunking configuration is provided, the content is split into
    /// overlapping chunks for efficient processing. Each chunk contains the text,
    /// optional embeddings (if enabled), and metadata about its position.
    #[pyo3(get)]
    pub chunks: Option<Vec<Chunk>>,
    /// Extracted images from the document.
    ///
    /// When image extraction is enabled via `ImageExtractionConfig`, this field
    /// contains all images found in the document with their raw data and metadata.
    /// Each image may optionally contain a nested `ocr_result` if OCR was performed.
    #[pyo3(get)]
    #[serde(skip)]
    pub images: Option<Vec<ExtractedImage>>,
    /// Per-page content when page extraction is enabled.
    ///
    /// When page extraction is configured, the document is split into per-page content
    /// with tables and images mapped to their respective pages.
    #[pyo3(get)]
    pub pages: Option<Vec<PageContent>>,
    /// Semantic elements when element-based result format is enabled.
    ///
    /// When result_format is set to ElementBased, this field contains semantic
    /// elements with type classification, unique identifiers, and metadata for
    /// Unstructured-compatible element-based processing.
    #[pyo3(get)]
    pub elements: Option<Vec<Element>>,
    /// Rich Djot content structure (when extracting Djot documents).
    ///
    /// When extracting Djot documents with structured extraction enabled,
    /// this field contains the full semantic structure including:
    /// - Block-level elements with nesting
    /// - Inline formatting with attributes
    /// - Links, images, footnotes
    /// - Math expressions
    /// - Complete attribute information
    ///
    /// The `content` field still contains plain text for backward compatibility.
    ///
    /// Always `None` for non-Djot documents.
    #[pyo3(get)]
    #[serde(skip)]
    pub djot_content: Option<DjotContent>,
    /// OCR elements with full spatial and confidence metadata.
    ///
    /// When OCR is performed with element extraction enabled, this field contains
    /// the structured representation of detected text including:
    /// - Bounding geometry (rectangles or quadrilaterals)
    /// - Confidence scores (detection and recognition)
    /// - Rotation information
    /// - Hierarchical relationships (Tesseract only)
    ///
    /// This field preserves all metadata that would otherwise be lost when
    /// converting to plain text or markdown output formats.
    ///
    /// Only populated when `OcrElementConfig.include_elements` is true.
    #[pyo3(get)]
    #[serde(skip)]
    pub ocr_elements: Option<Vec<OcrElement>>,
    /// Structured document tree (when document structure extraction is enabled).
    ///
    /// When `include_document_structure` is true in `ExtractionConfig`, this field
    /// contains the full hierarchical representation of the document including:
    /// - Heading-driven section nesting
    /// - Table grids with cell-level metadata
    /// - Content layer classification (body, header, footer, footnote)
    /// - Inline text annotations (formatting, links)
    /// - Bounding boxes and page numbers
    ///
    /// Independent of `result_format` — can be combined with Unified or ElementBased.
    #[pyo3(get)]
    #[serde(skip)]
    pub document: Option<DocumentStructure>,
    /// Extracted keywords when keyword extraction is enabled.
    ///
    /// When keyword extraction (RAKE or YAKE) is configured, this field contains
    /// the extracted keywords with scores, algorithm info, and position data.
    /// Previously stored in `metadata.additional["keywords"]`.
    #[pyo3(get)]
    pub extracted_keywords: Option<Vec<Keyword>>,
    /// Document quality score from quality analysis.
    ///
    /// A value between 0.0 and 1.0 indicating the overall text quality.
    /// Previously stored in `metadata.additional["quality_score"]`.
    #[pyo3(get)]
    pub quality_score: Option<f64>,
    /// Non-fatal warnings collected during processing pipeline stages.
    ///
    /// Captures errors from optional pipeline features (embedding, chunking,
    /// language detection, output formatting) that don't prevent extraction
    /// but may indicate degraded results.
    /// Previously stored as individual keys in `metadata.additional`.
    #[pyo3(get)]
    pub processing_warnings: Vec<ProcessingWarning>,
    /// PDF annotations extracted from the document.
    ///
    /// When annotation extraction is enabled via `PdfConfig::extract_annotations`,
    /// this field contains text notes, highlights, links, stamps, and other
    /// annotations found in PDF documents.
    #[pyo3(get)]
    pub annotations: Option<Vec<PdfAnnotation>>,
    /// Nested extraction results from archive contents.
    ///
    /// When extracting archives, each processable file inside produces its own
    /// full extraction result. Set to `None` for non-archive formats.
    /// Use `max_archive_depth` in config to control recursion depth.
    #[pyo3(get)]
    #[serde(skip)]
    pub children: Option<Vec<ArchiveEntry>>,
    /// URIs/links discovered during document extraction.
    ///
    /// Contains hyperlinks, image references, citations, email addresses, and
    /// other URI-like references found in the document. Always extracted when
    /// present in the source document.
    #[pyo3(get)]
    pub uris: Option<Vec<ExtractedUri>>,
    /// Tracked changes embedded in the source document.
    ///
    /// Populated by per-format extractors that understand change-tracking
    /// metadata (DOCX `w:ins`/`w:del`/`w:rPrChange`, ODT `text:change-*`,
    /// …). Every extractor defaults to `None` until its format-specific
    /// implementation is added. Extractors that do populate this field follow
    /// the "accepted-changes" convention: inserted text is present in
    /// `content`, deleted text is absent — the revision list is the separate
    /// audit trail.
    #[pyo3(get)]
    #[serde(skip)]
    pub revisions: Option<Vec<DocumentRevision>>,
    /// Structured extraction output from LLM-based JSON schema extraction.
    ///
    /// When `structured_extraction` is configured in `ExtractionConfig`, the
    /// extracted document content is sent to a VLM with the provided JSON schema.
    /// The response is parsed and stored here as a JSON value matching the schema.
    #[pyo3(get)]
    #[serde(default, deserialize_with = "alef_json_str_opt::deserialize")]
    pub structured_output: Option<String>,
    /// Code intelligence results from tree-sitter analysis.
    ///
    /// Populated when extracting source code files with the `tree-sitter` feature.
    /// Contains metrics, structural analysis, imports/exports, comments,
    /// docstrings, symbols, diagnostics, and optionally chunked code segments.
    ///
    /// Stored as an opaque JSON value so that all language bindings (Go, Java,
    /// C#, …) can deserialize it as a raw JSON object rather than a typed struct.
    /// The underlying type is `tree_sitter_language_pack::ProcessResult`.
    #[pyo3(get)]
    #[serde(default, deserialize_with = "alef_json_str_opt::deserialize")]
    pub code_intelligence: Option<String>,
    /// LLM token usage and cost data for all LLM calls made during this extraction.
    ///
    /// Contains one entry per LLM call. Multiple entries are produced when
    /// VLM OCR, structured extraction, or LLM embeddings run during
    /// the same extraction.
    ///
    /// `None` when no LLM was used.
    #[pyo3(get)]
    pub llm_usage: Option<Vec<LlmUsage>>,
    /// Pre-rendered content in the requested output format.
    ///
    /// Populated during `derive_extraction_result` before tree derivation consumes
    /// element data. `apply_output_format` swaps this into `content` at the end
    /// of the pipeline, after post-processors have operated on plain text.
    #[pyo3(get)]
    pub formatted_content: Option<String>,
    /// Structured hOCR document for the OCR+layout pipeline.
    ///
    /// When tesseract produces hOCR output, the parsed `InternalDocument` carries
    /// paragraph structure with bounding boxes and confidence scores. The layout
    /// classification step enriches these elements before final rendering.
    #[pyo3(get)]
    #[serde(skip)]
    pub ocr_internal_document: Option<String>,
}

#[pymethods]
impl ExtractionResult {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content=Self::default().content, mime_type=Self::default().mime_type, metadata=None, tables=Self::default().tables, processing_warnings=Self::default().processing_warnings, extraction_method=None, detected_languages=None, chunks=None, images=None, pages=None, elements=None, djot_content=None, ocr_elements=None, document=None, extracted_keywords=None, quality_score=None, annotations=None, children=None, uris=None, revisions=None, structured_output=None, code_intelligence=None, llm_usage=None, formatted_content=None, ocr_internal_document=None))]
    #[new]
    pub fn new(
        content: String,
        mime_type: String,
        metadata: Option<Metadata>,
        tables: Vec<Table>,
        processing_warnings: Vec<ProcessingWarning>,
        extraction_method: Option<ExtractionMethod>,
        detected_languages: Option<Vec<String>>,
        chunks: Option<Vec<Chunk>>,
        images: Option<Vec<ExtractedImage>>,
        pages: Option<Vec<PageContent>>,
        elements: Option<Vec<Element>>,
        djot_content: Option<DjotContent>,
        ocr_elements: Option<Vec<OcrElement>>,
        document: Option<DocumentStructure>,
        extracted_keywords: Option<Vec<Keyword>>,
        quality_score: Option<f64>,
        annotations: Option<Vec<PdfAnnotation>>,
        children: Option<Vec<ArchiveEntry>>,
        uris: Option<Vec<ExtractedUri>>,
        revisions: Option<Vec<DocumentRevision>>,
        structured_output: Option<String>,
        code_intelligence: Option<String>,
        llm_usage: Option<Vec<LlmUsage>>,
        formatted_content: Option<String>,
        ocr_internal_document: Option<String>,
    ) -> Self {
        Self {
            content,
            mime_type,
            metadata: metadata.unwrap_or_else(|| Self::default().metadata),
            extraction_method,
            tables,
            detected_languages,
            chunks,
            images,
            pages,
            elements,
            djot_content,
            ocr_elements,
            document,
            extracted_keywords,
            quality_score,
            processing_warnings,
            annotations,
            children,
            uris,
            revisions,
            structured_output,
            code_intelligence,
            llm_usage,
            formatted_content,
            ocr_internal_document,
        }
    }

    #[staticmethod]
    #[pyo3(signature = (ocr))]
    pub fn from_ocr(ocr: OcrExtractionResult) -> ExtractionResult {
        let ocr_core: kreuzberg::OcrExtractionResult = ocr.into();

        kreuzberg::ExtractionResult::from_ocr(ocr_core).into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ArchiveEntry {
    /// Archive-relative file path (e.g. "folder/document.pdf").
    #[pyo3(get)]
    pub path: String,
    /// Detected MIME type of the file.
    #[pyo3(get)]
    pub mime_type: String,
    /// Full extraction result for this file.
    #[pyo3(get)]
    #[serde(skip)]
    pub result: ExtractionResult,
}

#[pymethods]
impl ArchiveEntry {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (path, mime_type, result))]
    #[new]
    pub fn new(path: String, mime_type: String, result: ExtractionResult) -> Self {
        Self {
            path,
            mime_type,
            result,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ProcessingWarning {
    /// The pipeline stage or feature that produced this warning
    /// (e.g., "embedding", "chunking", "language_detection", "output_format").
    #[pyo3(get)]
    pub source: String,
    /// Human-readable description of what went wrong.
    #[pyo3(get)]
    pub message: String,
}

#[pymethods]
impl ProcessingWarning {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (source, message))]
    #[new]
    pub fn new(source: String, message: String) -> Self {
        Self { source, message }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct LlmUsage {
    /// The LLM model identifier (e.g. "openai/gpt-4o", "anthropic/claude-sonnet-4-20250514").
    #[pyo3(get)]
    pub model: String,
    /// The pipeline stage that triggered this LLM call
    /// (e.g. "vlm_ocr", "structured_extraction", "embeddings").
    #[pyo3(get)]
    pub source: String,
    /// Number of input/prompt tokens consumed.
    #[pyo3(get)]
    pub input_tokens: Option<u64>,
    /// Number of output/completion tokens generated.
    #[pyo3(get)]
    pub output_tokens: Option<u64>,
    /// Total tokens (input + output).
    #[pyo3(get)]
    pub total_tokens: Option<u64>,
    /// Estimated cost in USD based on the provider's published pricing.
    #[pyo3(get)]
    pub estimated_cost: Option<f64>,
    /// Why the model stopped generating (e.g. "stop", "length", "content_filter").
    #[pyo3(get)]
    pub finish_reason: Option<String>,
}

#[pymethods]
impl LlmUsage {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (model=Self::default().model, source=Self::default().source, input_tokens=None, output_tokens=None, total_tokens=None, estimated_cost=None, finish_reason=None))]
    #[new]
    pub fn new(
        model: String,
        source: String,
        input_tokens: Option<u64>,
        output_tokens: Option<u64>,
        total_tokens: Option<u64>,
        estimated_cost: Option<f64>,
        finish_reason: Option<String>,
    ) -> Self {
        Self {
            model,
            source,
            input_tokens,
            output_tokens,
            total_tokens,
            estimated_cost,
            finish_reason,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct Chunk {
    /// The text content of this chunk.
    #[pyo3(get)]
    pub content: String,
    /// Semantic structural classification of this chunk.
    ///
    /// Assigned by the heuristic classifier based on content patterns and
    /// heading context. Defaults to `ChunkType::Unknown` when no rule matches.
    #[pyo3(get)]
    pub chunk_type: ChunkType,
    /// Optional embedding vector for this chunk.
    ///
    /// Only populated when `EmbeddingConfig` is provided in chunking configuration.
    /// The dimensionality depends on the chosen embedding model.
    #[pyo3(get)]
    pub embedding: Option<Vec<f32>>,
    /// Metadata about this chunk's position and properties.
    #[pyo3(get)]
    pub metadata: ChunkMetadata,
}

#[pymethods]
impl Chunk {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content, chunk_type, metadata, embedding=None))]
    #[new]
    pub fn new(content: String, chunk_type: ChunkType, metadata: ChunkMetadata, embedding: Option<Vec<f32>>) -> Self {
        Self {
            content,
            chunk_type,
            embedding,
            metadata,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct HeadingContext {
    /// The heading hierarchy from document root to this chunk's section.
    /// Index 0 is the outermost (h1), last element is the most specific.
    #[pyo3(get)]
    pub headings: Vec<HeadingLevel>,
}

#[pymethods]
impl HeadingContext {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (headings))]
    #[new]
    pub fn new(headings: Vec<HeadingLevel>) -> Self {
        Self { headings }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct HeadingLevel {
    /// Heading depth (1 = h1, 2 = h2, etc.)
    #[pyo3(get)]
    pub level: u8,
    /// The text content of the heading.
    #[pyo3(get)]
    pub text: String,
}

#[pymethods]
impl HeadingLevel {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (level, text))]
    #[new]
    pub fn new(level: u8, text: String) -> Self {
        Self { level, text }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ChunkMetadata {
    /// Byte offset where this chunk starts in the original text (UTF-8 valid boundary).
    #[pyo3(get)]
    pub byte_start: usize,
    /// Byte offset where this chunk ends in the original text (UTF-8 valid boundary).
    #[pyo3(get)]
    pub byte_end: usize,
    /// Number of tokens in this chunk (if available).
    ///
    /// This is calculated by the embedding model's tokenizer if embeddings are enabled.
    #[pyo3(get)]
    pub token_count: Option<usize>,
    /// Zero-based index of this chunk in the document.
    #[pyo3(get)]
    pub chunk_index: usize,
    /// Total number of chunks in the document.
    #[pyo3(get)]
    pub total_chunks: usize,
    /// First page number this chunk spans (1-indexed).
    ///
    /// Only populated when page tracking is enabled in extraction configuration.
    #[pyo3(get)]
    pub first_page: Option<u32>,
    /// Last page number this chunk spans (1-indexed, equal to first_page for single-page chunks).
    ///
    /// Only populated when page tracking is enabled in extraction configuration.
    #[pyo3(get)]
    pub last_page: Option<u32>,
    /// Heading context when using Markdown chunker.
    ///
    /// Contains the heading hierarchy this chunk falls under.
    /// Only populated when `ChunkerType::Markdown` is used.
    #[pyo3(get)]
    pub heading_context: Option<HeadingContext>,
    /// Indices into `ExtractionResult.images` for images on pages covered by this chunk.
    ///
    /// Contains zero-based indices into the top-level `images` collection for every
    /// image whose `page_number` falls within `[first_page, last_page]`.
    /// Empty when image extraction is disabled or the chunk spans no pages with images.
    #[pyo3(get)]
    pub image_indices: Vec<u32>,
}

#[pymethods]
impl ChunkMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (byte_start, byte_end, chunk_index, total_chunks, image_indices, token_count=None, first_page=None, last_page=None, heading_context=None))]
    #[new]
    pub fn new(
        byte_start: usize,
        byte_end: usize,
        chunk_index: usize,
        total_chunks: usize,
        image_indices: Vec<u32>,
        token_count: Option<usize>,
        first_page: Option<u32>,
        last_page: Option<u32>,
        heading_context: Option<HeadingContext>,
    ) -> Self {
        Self {
            byte_start,
            byte_end,
            token_count,
            chunk_index,
            total_chunks,
            first_page,
            last_page,
            heading_context,
            image_indices,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ExtractedImage {
    /// Raw image data (PNG, JPEG, WebP, etc. bytes).
    /// Uses `bytes::Bytes` for cheap cloning of large buffers.
    #[pyo3(get)]
    pub data: Vec<u8>,
    /// Image format (e.g., "jpeg", "png", "webp")
    /// Uses Cow<'static, str> to avoid allocation for static literals.
    #[pyo3(get)]
    pub format: String,
    /// Zero-indexed position of this image in the document/page
    #[pyo3(get)]
    pub image_index: u32,
    /// Page/slide number where image was found (1-indexed)
    #[pyo3(get)]
    pub page_number: Option<u32>,
    /// Image width in pixels
    #[pyo3(get)]
    pub width: Option<u32>,
    /// Image height in pixels
    #[pyo3(get)]
    pub height: Option<u32>,
    /// Colorspace information (e.g., "RGB", "CMYK", "Gray")
    #[pyo3(get)]
    pub colorspace: Option<String>,
    /// Bits per color component (e.g., 8, 16)
    #[pyo3(get)]
    pub bits_per_component: Option<u32>,
    /// Whether this image is a mask image
    #[pyo3(get)]
    pub is_mask: bool,
    /// Optional description of the image
    #[pyo3(get)]
    pub description: Option<String>,
    /// Nested OCR extraction result (if image was OCRed)
    ///
    /// When OCR is performed on this image, the result is embedded here
    /// rather than in a separate collection, making the relationship explicit.
    #[pyo3(get)]
    #[serde(skip)]
    pub ocr_result: Option<ExtractionResult>,
    /// Bounding box of the image on the page (PDF coordinates: x0=left, y0=bottom, x1=right, y1=top).
    /// Only populated for PDF-extracted images when position data is available from the PDF extractor.
    #[pyo3(get)]
    pub bounding_box: Option<BoundingBox>,
    /// Original source path of the image within the document archive (e.g., "media/image1.png" in DOCX).
    /// Used for rendering image references when the binary data is not extracted.
    #[pyo3(get)]
    pub source_path: Option<String>,
    /// Heuristic classification of what this image likely depicts.
    /// `None` if classification was disabled or inconclusive.
    #[pyo3(get)]
    pub image_kind: Option<ImageKind>,
    /// Confidence score for `image_kind`, in the range 0.0 to 1.0.
    #[pyo3(get)]
    pub kind_confidence: Option<f32>,
    /// Identifier shared across images that form a single logical figure
    /// (e.g. all raster tiles of one technical drawing). `None` for singletons.
    #[pyo3(get)]
    pub cluster_id: Option<u32>,
}

#[pymethods]
impl ExtractedImage {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (data, format, image_index, is_mask, page_number=None, width=None, height=None, colorspace=None, bits_per_component=None, description=None, ocr_result=None, bounding_box=None, source_path=None, image_kind=None, kind_confidence=None, cluster_id=None))]
    #[new]
    pub fn new(
        data: Vec<u8>,
        format: String,
        image_index: u32,
        is_mask: bool,
        page_number: Option<u32>,
        width: Option<u32>,
        height: Option<u32>,
        colorspace: Option<String>,
        bits_per_component: Option<u32>,
        description: Option<String>,
        ocr_result: Option<ExtractionResult>,
        bounding_box: Option<BoundingBox>,
        source_path: Option<String>,
        image_kind: Option<ImageKind>,
        kind_confidence: Option<f32>,
        cluster_id: Option<u32>,
    ) -> Self {
        Self {
            data,
            format,
            image_index,
            page_number,
            width,
            height,
            colorspace,
            bits_per_component,
            is_mask,
            description,
            ocr_result,
            bounding_box,
            source_path,
            image_kind,
            kind_confidence,
            cluster_id,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct BoundingBox {
    /// Left x-coordinate
    #[pyo3(get)]
    pub x0: f64,
    /// Bottom y-coordinate
    #[pyo3(get)]
    pub y0: f64,
    /// Right x-coordinate
    #[pyo3(get)]
    pub x1: f64,
    /// Top y-coordinate
    #[pyo3(get)]
    pub y1: f64,
}

#[pymethods]
impl BoundingBox {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (x0=Self::default().x0, y0=Self::default().y0, x1=Self::default().x1, y1=Self::default().y1))]
    #[new]
    pub fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Self {
        Self { x0, y0, x1, y1 }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ElementMetadata {
    /// Page number (1-indexed)
    #[pyo3(get)]
    pub page_number: Option<u32>,
    /// Source filename or document name
    #[pyo3(get)]
    pub filename: Option<String>,
    /// Bounding box coordinates if available
    #[pyo3(get)]
    pub coordinates: Option<BoundingBox>,
    /// Position index in the element sequence
    #[pyo3(get)]
    pub element_index: Option<usize>,
    /// Additional custom metadata
    #[pyo3(get)]
    pub additional: HashMap<String, String>,
}

#[pymethods]
impl ElementMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (additional, page_number=None, filename=None, coordinates=None, element_index=None))]
    #[new]
    pub fn new(
        additional: HashMap<String, String>,
        page_number: Option<u32>,
        filename: Option<String>,
        coordinates: Option<BoundingBox>,
        element_index: Option<usize>,
    ) -> Self {
        Self {
            page_number,
            filename,
            coordinates,
            element_index,
            additional,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct Element {
    /// Unique element identifier
    #[pyo3(get)]
    #[serde(skip)]
    pub element_id: String,
    /// Semantic type of this element
    #[pyo3(get)]
    pub element_type: ElementType,
    /// Text content of the element
    #[pyo3(get)]
    pub text: String,
    /// Metadata about the element
    #[pyo3(get)]
    pub metadata: ElementMetadata,
}

#[pymethods]
impl Element {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (element_id, element_type, text, metadata))]
    #[new]
    pub fn new(element_id: String, element_type: ElementType, text: String, metadata: ElementMetadata) -> Self {
        Self {
            element_id,
            element_type,
            text,
            metadata,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ExcelWorkbook {
    /// All sheets in the workbook
    #[pyo3(get)]
    pub sheets: Vec<ExcelSheet>,
    /// Workbook-level metadata (author, creation date, etc.)
    #[pyo3(get)]
    pub metadata: HashMap<String, String>,
    /// Collaborative-edit revision headers from `xl/revisions/revisionHeaders.xml`.
    ///
    /// Populated for legacy shared-workbook `.xlsx` files that contain the
    /// `xl/revisions/` directory. Each `<header>` element maps to one
    /// `DocumentRevision { kind: FormatChange }` carrying the header's `guid`
    /// (→ `revision_id`), `userName` (→ `author`), and `dateTime` (→ `timestamp`).
    /// `anchor` and `delta` are `None`/empty for v1 (per-cell log parsing is a
    /// follow-up). `None` when `xl/revisions/revisionHeaders.xml` is absent.
    #[pyo3(get)]
    #[serde(skip)]
    pub revisions: Option<Vec<DocumentRevision>>,
}

#[pymethods]
impl ExcelWorkbook {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (sheets, metadata, revisions=None))]
    #[new]
    pub fn new(
        sheets: Vec<ExcelSheet>,
        metadata: HashMap<String, String>,
        revisions: Option<Vec<DocumentRevision>>,
    ) -> Self {
        Self {
            sheets,
            metadata,
            revisions,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct ExcelSheet {
    /// Sheet name as it appears in Excel
    #[pyo3(get)]
    pub name: String,
    /// Sheet content converted to Markdown tables
    #[pyo3(get)]
    pub markdown: String,
    /// Number of rows
    #[pyo3(get)]
    pub row_count: usize,
    /// Number of columns
    #[pyo3(get)]
    pub col_count: usize,
    /// Total number of non-empty cells
    #[pyo3(get)]
    pub cell_count: usize,
    /// Pre-extracted table cells (2D vector of cell values)
    /// Populated during markdown generation to avoid re-parsing markdown.
    /// None for empty sheets.
    #[pyo3(get)]
    pub table_cells: Option<Vec<Vec<String>>>,
}

#[pymethods]
impl ExcelSheet {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (name, markdown, row_count, col_count, cell_count, table_cells=None))]
    #[new]
    pub fn new(
        name: String,
        markdown: String,
        row_count: usize,
        col_count: usize,
        cell_count: usize,
        table_cells: Option<Vec<Vec<String>>>,
    ) -> Self {
        Self {
            name,
            markdown,
            row_count,
            col_count,
            cell_count,
            table_cells,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct XmlExtractionResult {
    /// Extracted text content (XML structure filtered out)
    #[pyo3(get)]
    pub content: String,
    /// Total number of XML elements processed
    #[pyo3(get)]
    pub element_count: usize,
    /// List of unique element names found (sorted)
    #[pyo3(get)]
    pub unique_elements: Vec<String>,
}

#[pymethods]
impl XmlExtractionResult {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content, element_count, unique_elements))]
    #[new]
    pub fn new(content: String, element_count: usize, unique_elements: Vec<String>) -> Self {
        Self {
            content,
            element_count,
            unique_elements,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct TextExtractionResult {
    /// Extracted text content
    #[pyo3(get)]
    pub content: String,
    /// Number of lines
    #[pyo3(get)]
    pub line_count: usize,
    /// Number of words
    #[pyo3(get)]
    pub word_count: usize,
    /// Number of characters
    #[pyo3(get)]
    pub character_count: usize,
    /// Markdown headers (text only, Markdown files only)
    #[pyo3(get)]
    pub headers: Option<Vec<String>>,
    /// Markdown links as (text, URL) tuples (Markdown files only)
    #[pyo3(get)]
    #[serde(skip)]
    pub links: Option<Vec<Vec<String>>>,
    /// Code blocks as (language, code) tuples (Markdown files only)
    #[pyo3(get)]
    #[serde(skip)]
    pub code_blocks: Option<Vec<Vec<String>>>,
}

#[pymethods]
impl TextExtractionResult {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content, line_count, word_count, character_count, headers=None, links=None, code_blocks=None))]
    #[new]
    pub fn new(
        content: String,
        line_count: usize,
        word_count: usize,
        character_count: usize,
        headers: Option<Vec<String>>,
        links: Option<Vec<Vec<String>>>,
        code_blocks: Option<Vec<Vec<String>>>,
    ) -> Self {
        Self {
            content,
            line_count,
            word_count,
            character_count,
            headers,
            links,
            code_blocks,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PptxExtractionResult {
    /// Extracted text content from all slides
    #[pyo3(get)]
    pub content: String,
    /// Presentation metadata
    #[pyo3(get)]
    pub metadata: PptxMetadata,
    /// Total number of slides
    #[pyo3(get)]
    pub slide_count: usize,
    /// Total number of embedded images
    #[pyo3(get)]
    pub image_count: usize,
    /// Total number of tables
    #[pyo3(get)]
    pub table_count: usize,
    /// Extracted images from the presentation
    #[pyo3(get)]
    #[serde(skip)]
    pub images: Vec<ExtractedImage>,
    /// Slide structure with boundaries (when page tracking is enabled)
    #[pyo3(get)]
    pub page_structure: Option<PageStructure>,
    /// Per-slide content (when page tracking is enabled)
    #[pyo3(get)]
    pub page_contents: Option<Vec<PageContent>>,
    /// Structured document representation
    #[pyo3(get)]
    #[serde(skip)]
    pub document: Option<DocumentStructure>,
    /// Hyperlinks discovered in slides as (url, optional_label) pairs.
    #[pyo3(get)]
    #[serde(skip)]
    pub hyperlinks: Vec<String>,
    /// Office metadata extracted from docProps/core.xml and docProps/app.xml.
    ///
    /// Contains keys like "title", "author", "created_by", "subject", "keywords",
    /// "modified_by", "created_at", "modified_at", etc.
    #[pyo3(get)]
    pub office_metadata: HashMap<String, String>,
    /// Slide comments as revisions.
    ///
    /// Each `<p:cm>` element in `ppt/comments/comment{N}.xml` becomes a
    /// `DocumentRevision { kind: Comment }` with author (resolved from
    /// `ppt/commentAuthors.xml`), ISO-8601 timestamp, and
    /// `RevisionAnchor::Slide { index }`. `None` when no comment XML parts exist.
    #[pyo3(get)]
    #[serde(skip)]
    pub revisions: Option<Vec<DocumentRevision>>,
}

#[pymethods]
impl PptxExtractionResult {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content, metadata, slide_count, image_count, table_count, images, hyperlinks, office_metadata, page_structure=None, page_contents=None, document=None, revisions=None))]
    #[new]
    pub fn new(
        content: String,
        metadata: PptxMetadata,
        slide_count: usize,
        image_count: usize,
        table_count: usize,
        images: Vec<ExtractedImage>,
        hyperlinks: Vec<String>,
        office_metadata: HashMap<String, String>,
        page_structure: Option<PageStructure>,
        page_contents: Option<Vec<PageContent>>,
        document: Option<DocumentStructure>,
        revisions: Option<Vec<DocumentRevision>>,
    ) -> Self {
        Self {
            content,
            metadata,
            slide_count,
            image_count,
            table_count,
            images,
            page_structure,
            page_contents,
            document,
            hyperlinks,
            office_metadata,
            revisions,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct EmailExtractionResult {
    /// Email subject line
    #[pyo3(get)]
    pub subject: Option<String>,
    /// Sender email address
    #[pyo3(get)]
    pub from_email: Option<String>,
    /// Primary recipient email addresses
    #[pyo3(get)]
    pub to_emails: Vec<String>,
    /// CC recipient email addresses
    #[pyo3(get)]
    pub cc_emails: Vec<String>,
    /// BCC recipient email addresses
    #[pyo3(get)]
    pub bcc_emails: Vec<String>,
    /// Email date/timestamp
    #[pyo3(get)]
    pub date: Option<String>,
    /// Message-ID header value
    #[pyo3(get)]
    pub message_id: Option<String>,
    /// Plain text version of the email body
    #[pyo3(get)]
    pub plain_text: Option<String>,
    /// HTML version of the email body
    #[pyo3(get)]
    pub html_content: Option<String>,
    /// Cleaned/processed text content. Aliased as `cleaned_text` for back-compat.
    #[pyo3(get)]
    pub content: String,
    /// List of email attachments
    #[pyo3(get)]
    pub attachments: Vec<EmailAttachment>,
    /// Additional email headers and metadata
    #[pyo3(get)]
    pub metadata: HashMap<String, String>,
}

#[pymethods]
impl EmailExtractionResult {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (to_emails, cc_emails, bcc_emails, content, attachments, metadata, subject=None, from_email=None, date=None, message_id=None, plain_text=None, html_content=None))]
    #[new]
    pub fn new(
        to_emails: Vec<String>,
        cc_emails: Vec<String>,
        bcc_emails: Vec<String>,
        content: String,
        attachments: Vec<EmailAttachment>,
        metadata: HashMap<String, String>,
        subject: Option<String>,
        from_email: Option<String>,
        date: Option<String>,
        message_id: Option<String>,
        plain_text: Option<String>,
        html_content: Option<String>,
    ) -> Self {
        Self {
            subject,
            from_email,
            to_emails,
            cc_emails,
            bcc_emails,
            date,
            message_id,
            plain_text,
            html_content,
            content,
            attachments,
            metadata,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct EmailAttachment {
    /// Attachment name (from Content-Disposition header)
    #[pyo3(get)]
    pub name: Option<String>,
    /// Filename of the attachment
    #[pyo3(get)]
    pub filename: Option<String>,
    /// MIME type of the attachment
    #[pyo3(get)]
    pub mime_type: Option<String>,
    /// Size in bytes
    #[pyo3(get)]
    pub size: Option<usize>,
    /// Whether this attachment is an image
    #[pyo3(get)]
    pub is_image: bool,
    /// Attachment data (if extracted).
    /// Uses `bytes::Bytes` for cheap cloning of large buffers.
    #[pyo3(get)]
    pub data: Option<Vec<u8>>,
}

#[pymethods]
impl EmailAttachment {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (is_image, name=None, filename=None, mime_type=None, size=None, data=None))]
    #[new]
    pub fn new(
        is_image: bool,
        name: Option<String>,
        filename: Option<String>,
        mime_type: Option<String>,
        size: Option<usize>,
        data: Option<Vec<u8>>,
    ) -> Self {
        Self {
            name,
            filename,
            mime_type,
            size,
            is_image,
            data,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OcrExtractionResult {
    /// Recognized text content
    #[pyo3(get)]
    pub content: String,
    /// Original MIME type of the processed image
    #[pyo3(get)]
    pub mime_type: String,
    /// OCR processing metadata (confidence scores, language, etc.)
    #[pyo3(get)]
    pub metadata: HashMap<String, String>,
    /// Tables detected and extracted via OCR
    #[pyo3(get)]
    pub tables: Vec<OcrTable>,
    /// Structured OCR elements with bounding boxes and confidence scores.
    /// Available when TSV output is requested or table detection is enabled.
    #[pyo3(get)]
    #[serde(skip)]
    pub ocr_elements: Option<Vec<OcrElement>>,
    /// Structured document produced from hOCR parsing.
    /// Carries paragraph structure, bounding boxes, and confidence scores
    /// that the flattened `content` string discards.
    #[pyo3(get)]
    #[serde(skip)]
    pub internal_document: Option<String>,
}

#[pymethods]
impl OcrExtractionResult {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content, mime_type, metadata, tables, ocr_elements=None, internal_document=None))]
    #[new]
    pub fn new(
        content: String,
        mime_type: String,
        metadata: HashMap<String, String>,
        tables: Vec<OcrTable>,
        ocr_elements: Option<Vec<OcrElement>>,
        internal_document: Option<String>,
    ) -> Self {
        Self {
            content,
            mime_type,
            metadata,
            tables,
            ocr_elements,
            internal_document,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OcrTable {
    /// Table cells as a 2D vector (rows × columns)
    #[pyo3(get)]
    pub cells: Vec<Vec<String>>,
    /// Markdown representation of the table
    #[pyo3(get)]
    pub markdown: String,
    /// Page number where the table was found (1-indexed)
    #[pyo3(get)]
    pub page_number: u32,
    /// Bounding box of the table in pixel coordinates (from OCR word positions).
    #[pyo3(get)]
    pub bounding_box: Option<OcrTableBoundingBox>,
}

#[pymethods]
impl OcrTable {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (cells, markdown, page_number, bounding_box=None))]
    #[new]
    pub fn new(
        cells: Vec<Vec<String>>,
        markdown: String,
        page_number: u32,
        bounding_box: Option<OcrTableBoundingBox>,
    ) -> Self {
        Self {
            cells,
            markdown,
            page_number,
            bounding_box,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OcrTableBoundingBox {
    /// Left x-coordinate (pixels)
    #[pyo3(get)]
    pub left: u32,
    /// Top y-coordinate (pixels)
    #[pyo3(get)]
    pub top: u32,
    /// Right x-coordinate (pixels)
    #[pyo3(get)]
    pub right: u32,
    /// Bottom y-coordinate (pixels)
    #[pyo3(get)]
    pub bottom: u32,
}

#[pymethods]
impl OcrTableBoundingBox {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (left, top, right, bottom))]
    #[new]
    pub fn new(left: u32, top: u32, right: u32, bottom: u32) -> Self {
        Self {
            left,
            top,
            right,
            bottom,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ImagePreprocessingConfig {
    /// Target DPI for the image (300 is standard, 600 for small text).
    #[pyo3(get)]
    pub target_dpi: i32,
    /// Auto-detect and correct image rotation.
    #[pyo3(get)]
    pub auto_rotate: bool,
    /// Correct skew (tilted images).
    #[pyo3(get)]
    pub deskew: bool,
    /// Remove noise from the image.
    #[pyo3(get)]
    pub denoise: bool,
    /// Enhance contrast for better text visibility.
    #[pyo3(get)]
    pub contrast_enhance: bool,
    /// Binarization method: "otsu", "sauvola", "adaptive".
    #[pyo3(get)]
    pub binarization_method: String,
    /// Invert colors (white text on black → black on white).
    #[pyo3(get)]
    pub invert_colors: bool,
}

#[pymethods]
impl ImagePreprocessingConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (target_dpi=Self::default().target_dpi, auto_rotate=Self::default().auto_rotate, deskew=Self::default().deskew, denoise=Self::default().denoise, contrast_enhance=Self::default().contrast_enhance, binarization_method=Self::default().binarization_method, invert_colors=Self::default().invert_colors))]
    #[new]
    pub fn new(
        target_dpi: i32,
        auto_rotate: bool,
        deskew: bool,
        denoise: bool,
        contrast_enhance: bool,
        binarization_method: String,
        invert_colors: bool,
    ) -> Self {
        Self {
            target_dpi,
            auto_rotate,
            deskew,
            denoise,
            contrast_enhance,
            binarization_method,
            invert_colors,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> ImagePreprocessingConfig {
        kreuzberg::ImagePreprocessingConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct TesseractConfig {
    /// Language code (e.g., "eng", "deu", "fra")
    #[pyo3(get)]
    pub language: String,
    /// Page Segmentation Mode (0-13).
    ///
    /// Common values:
    /// - 3: Fully automatic page segmentation (native default)
    /// - 6: Assume a single uniform block of text (WASM default — avoids layout-analysis hang)
    /// - 11: Sparse text with no particular order
    #[pyo3(get)]
    pub psm: i32,
    /// Output format ("text" or "markdown")
    #[pyo3(get)]
    pub output_format: String,
    /// OCR Engine Mode (0-3).
    ///
    /// - 0: Legacy engine only
    /// - 1: Neural nets (LSTM) only (usually best)
    /// - 2: Legacy + LSTM
    /// - 3: Default (based on what's available)
    #[pyo3(get)]
    pub oem: i32,
    /// Minimum confidence threshold (0.0-100.0).
    ///
    /// Words with confidence below this threshold may be rejected or flagged.
    #[pyo3(get)]
    pub min_confidence: f64,
    /// Image preprocessing configuration.
    ///
    /// Controls how images are preprocessed before OCR. Can significantly
    /// improve quality for scanned documents or low-quality images.
    #[pyo3(get)]
    pub preprocessing: Option<ImagePreprocessingConfig>,
    /// Enable automatic table detection and reconstruction
    #[pyo3(get)]
    pub enable_table_detection: bool,
    /// Minimum confidence threshold for table detection (0.0-1.0)
    #[pyo3(get)]
    pub table_min_confidence: f64,
    /// Column threshold for table detection (pixels)
    #[pyo3(get)]
    pub table_column_threshold: i32,
    /// Row threshold ratio for table detection (0.0-1.0)
    #[pyo3(get)]
    pub table_row_threshold_ratio: f64,
    /// Enable OCR result caching
    #[pyo3(get)]
    pub use_cache: bool,
    /// Use pre-adapted templates for character classification
    #[pyo3(get)]
    pub classify_use_pre_adapted_templates: bool,
    /// Enable N-gram language model
    #[pyo3(get)]
    pub language_model_ngram_on: bool,
    /// Don't reject good words during block-level processing
    #[pyo3(get)]
    pub tessedit_dont_blkrej_good_wds: bool,
    /// Don't reject good words during row-level processing
    #[pyo3(get)]
    pub tessedit_dont_rowrej_good_wds: bool,
    /// Enable dictionary correction
    #[pyo3(get)]
    pub tessedit_enable_dict_correction: bool,
    /// Whitelist of allowed characters (empty = all allowed)
    #[pyo3(get)]
    pub tessedit_char_whitelist: String,
    /// Blacklist of forbidden characters (empty = none forbidden)
    #[pyo3(get)]
    pub tessedit_char_blacklist: String,
    /// Use primary language params model
    #[pyo3(get)]
    pub tessedit_use_primary_params_model: bool,
    /// Variable-width space detection
    #[pyo3(get)]
    pub textord_space_size_is_variable: bool,
    /// Use adaptive thresholding method
    #[pyo3(get)]
    pub thresholding_method: bool,
}

#[pymethods]
impl TesseractConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (language=Self::default().language, psm=Self::default().psm, output_format=Self::default().output_format, oem=Self::default().oem, min_confidence=Self::default().min_confidence, enable_table_detection=Self::default().enable_table_detection, table_min_confidence=Self::default().table_min_confidence, table_column_threshold=Self::default().table_column_threshold, table_row_threshold_ratio=Self::default().table_row_threshold_ratio, use_cache=Self::default().use_cache, classify_use_pre_adapted_templates=Self::default().classify_use_pre_adapted_templates, language_model_ngram_on=Self::default().language_model_ngram_on, tessedit_dont_blkrej_good_wds=Self::default().tessedit_dont_blkrej_good_wds, tessedit_dont_rowrej_good_wds=Self::default().tessedit_dont_rowrej_good_wds, tessedit_enable_dict_correction=Self::default().tessedit_enable_dict_correction, tessedit_char_whitelist=Self::default().tessedit_char_whitelist, tessedit_char_blacklist=Self::default().tessedit_char_blacklist, tessedit_use_primary_params_model=Self::default().tessedit_use_primary_params_model, textord_space_size_is_variable=Self::default().textord_space_size_is_variable, thresholding_method=Self::default().thresholding_method, preprocessing=None))]
    #[new]
    pub fn new(
        language: String,
        psm: i32,
        output_format: String,
        oem: i32,
        min_confidence: f64,
        enable_table_detection: bool,
        table_min_confidence: f64,
        table_column_threshold: i32,
        table_row_threshold_ratio: f64,
        use_cache: bool,
        classify_use_pre_adapted_templates: bool,
        language_model_ngram_on: bool,
        tessedit_dont_blkrej_good_wds: bool,
        tessedit_dont_rowrej_good_wds: bool,
        tessedit_enable_dict_correction: bool,
        tessedit_char_whitelist: String,
        tessedit_char_blacklist: String,
        tessedit_use_primary_params_model: bool,
        textord_space_size_is_variable: bool,
        thresholding_method: bool,
        preprocessing: Option<ImagePreprocessingConfig>,
    ) -> Self {
        Self {
            language,
            psm,
            output_format,
            oem,
            min_confidence,
            preprocessing,
            enable_table_detection,
            table_min_confidence,
            table_column_threshold,
            table_row_threshold_ratio,
            use_cache,
            classify_use_pre_adapted_templates,
            language_model_ngram_on,
            tessedit_dont_blkrej_good_wds,
            tessedit_dont_rowrej_good_wds,
            tessedit_enable_dict_correction,
            tessedit_char_whitelist,
            tessedit_char_blacklist,
            tessedit_use_primary_params_model,
            textord_space_size_is_variable,
            thresholding_method,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> TesseractConfig {
        kreuzberg::TesseractConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ImagePreprocessingMetadata {
    /// Original image dimensions (width, height) in pixels
    #[pyo3(get)]
    #[serde(skip)]
    pub original_dimensions: Vec<usize>,
    /// Original image DPI (horizontal, vertical)
    #[pyo3(get)]
    #[serde(skip)]
    pub original_dpi: Vec<f64>,
    /// Target DPI from configuration
    #[pyo3(get)]
    pub target_dpi: i32,
    /// Scaling factor applied to the image
    #[pyo3(get)]
    pub scale_factor: f64,
    /// Whether DPI was auto-adjusted based on content
    #[pyo3(get)]
    pub auto_adjusted: bool,
    /// Final DPI after processing
    #[pyo3(get)]
    pub final_dpi: i32,
    /// New dimensions after resizing (if resized)
    #[pyo3(get)]
    #[serde(skip)]
    pub new_dimensions: Option<Vec<usize>>,
    /// Resampling algorithm used ("LANCZOS3", "CATMULLROM", etc.)
    #[pyo3(get)]
    pub resample_method: String,
    /// Whether dimensions were clamped to max_image_dimension
    #[pyo3(get)]
    pub dimension_clamped: bool,
    /// Calculated optimal DPI (if auto_adjust_dpi enabled)
    #[pyo3(get)]
    pub calculated_dpi: Option<i32>,
    /// Whether resize was skipped (dimensions already optimal)
    #[pyo3(get)]
    pub skipped_resize: bool,
    /// Error message if resize failed
    #[pyo3(get)]
    pub resize_error: Option<String>,
}

#[pymethods]
impl ImagePreprocessingMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (original_dimensions, original_dpi, target_dpi, scale_factor, auto_adjusted, final_dpi, resample_method, dimension_clamped, skipped_resize, new_dimensions=None, calculated_dpi=None, resize_error=None))]
    #[new]
    pub fn new(
        original_dimensions: Vec<usize>,
        original_dpi: Vec<f64>,
        target_dpi: i32,
        scale_factor: f64,
        auto_adjusted: bool,
        final_dpi: i32,
        resample_method: String,
        dimension_clamped: bool,
        skipped_resize: bool,
        new_dimensions: Option<Vec<usize>>,
        calculated_dpi: Option<i32>,
        resize_error: Option<String>,
    ) -> Self {
        Self {
            original_dimensions,
            original_dpi,
            target_dpi,
            scale_factor,
            auto_adjusted,
            final_dpi,
            new_dimensions,
            resample_method,
            dimension_clamped,
            calculated_dpi,
            skipped_resize,
            resize_error,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct Metadata {
    /// Document title
    #[pyo3(get)]
    pub title: Option<String>,
    /// Document subject or description
    #[pyo3(get)]
    pub subject: Option<String>,
    /// Primary author(s) - always Vec for consistency
    #[pyo3(get)]
    pub authors: Option<Vec<String>>,
    /// Keywords/tags - always Vec for consistency
    #[pyo3(get)]
    pub keywords: Option<Vec<String>>,
    /// Primary language (ISO 639 code)
    #[pyo3(get)]
    pub language: Option<String>,
    /// Creation timestamp (ISO 8601 format)
    #[pyo3(get)]
    pub created_at: Option<String>,
    /// Last modification timestamp (ISO 8601 format)
    #[pyo3(get)]
    pub modified_at: Option<String>,
    /// User who created the document
    #[pyo3(get)]
    pub created_by: Option<String>,
    /// User who last modified the document
    #[pyo3(get)]
    pub modified_by: Option<String>,
    /// Page/slide/sheet structure with boundaries
    #[pyo3(get)]
    pub pages: Option<PageStructure>,
    /// Format-specific metadata (discriminated union)
    ///
    /// Contains detailed metadata specific to the document format.
    /// Serialized as a nested `"format"` object with a `format_type` discriminator field.
    #[pyo3(get)]
    pub format: Option<FormatMetadata>,
    /// Image preprocessing metadata (when OCR preprocessing was applied)
    #[pyo3(get)]
    pub image_preprocessing: Option<ImagePreprocessingMetadata>,
    /// JSON schema (for structured data extraction)
    #[pyo3(get)]
    #[serde(default, deserialize_with = "alef_json_str_opt::deserialize")]
    pub json_schema: Option<String>,
    /// Error metadata (for batch operations)
    #[pyo3(get)]
    pub error: Option<ErrorMetadata>,
    /// Extraction duration in milliseconds (for benchmarking).
    ///
    /// This field is populated by batch extraction to provide per-file timing
    /// information. It's `None` for single-file extraction (which uses external timing).
    #[pyo3(get)]
    pub extraction_duration_ms: Option<u64>,
    /// Document category (from frontmatter or classification).
    #[pyo3(get)]
    pub category: Option<String>,
    /// Document tags (from frontmatter).
    #[pyo3(get)]
    pub tags: Option<Vec<String>>,
    /// Document version string (from frontmatter).
    #[pyo3(get)]
    pub document_version: Option<String>,
    /// Abstract or summary text (from frontmatter).
    #[pyo3(get)]
    pub abstract_text: Option<String>,
    /// Output format identifier (e.g., "markdown", "html", "text").
    ///
    /// Set by the output format pipeline stage when format conversion is applied.
    /// Previously stored in `metadata.additional["output_format"]`.
    #[pyo3(get)]
    pub output_format: Option<String>,
    /// Whether OCR was used during extraction.
    ///
    /// Set to `true` whenever the extraction pipeline ran an OCR backend
    /// (Tesseract, PaddleOCR, VLM, etc.) and used that output as the primary
    /// or fallback text. `false` means native text extraction was used exclusively.
    #[pyo3(get)]
    pub ocr_used: bool,
    /// Additional custom fields from postprocessors.
    ///
    /// Serialized as a nested `"additional"` object (not flattened at root level).
    /// Uses `Cow<'static, str>` keys so static string keys avoid allocation.
    #[pyo3(get)]
    pub additional: HashMap<String, String>,
}

#[pymethods]
impl Metadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (ocr_used=Self::default().ocr_used, additional=Self::default().additional, title=None, subject=None, authors=None, keywords=None, language=None, created_at=None, modified_at=None, created_by=None, modified_by=None, pages=None, format=None, image_preprocessing=None, json_schema=None, error=None, extraction_duration_ms=None, category=None, tags=None, document_version=None, abstract_text=None, output_format=None))]
    #[new]
    pub fn new(
        ocr_used: bool,
        additional: HashMap<String, String>,
        title: Option<String>,
        subject: Option<String>,
        authors: Option<Vec<String>>,
        keywords: Option<Vec<String>>,
        language: Option<String>,
        created_at: Option<String>,
        modified_at: Option<String>,
        created_by: Option<String>,
        modified_by: Option<String>,
        pages: Option<PageStructure>,
        format: Option<FormatMetadata>,
        image_preprocessing: Option<ImagePreprocessingMetadata>,
        json_schema: Option<String>,
        error: Option<ErrorMetadata>,
        extraction_duration_ms: Option<u64>,
        category: Option<String>,
        tags: Option<Vec<String>>,
        document_version: Option<String>,
        abstract_text: Option<String>,
        output_format: Option<String>,
    ) -> Self {
        Self {
            title,
            subject,
            authors,
            keywords,
            language,
            created_at,
            modified_at,
            created_by,
            modified_by,
            pages,
            format,
            image_preprocessing,
            json_schema,
            error,
            extraction_duration_ms,
            category,
            tags,
            document_version,
            abstract_text,
            output_format,
            ocr_used,
            additional,
        }
    }

    #[pyo3(signature = ())]
    pub fn is_empty(&self) -> bool {
        let core_self = kreuzberg::Metadata {
            title: self.title.clone(),

            subject: self.subject.clone(),

            authors: self.authors.clone(),

            keywords: self.keywords.clone(),

            language: self.language.clone(),

            created_at: self.created_at.clone(),

            modified_at: self.modified_at.clone(),

            created_by: self.created_by.clone(),

            modified_by: self.modified_by.clone(),

            pages: self.pages.clone().map(Into::into),

            format: self.format.clone().map(Into::into),

            image_preprocessing: self.image_preprocessing.clone().map(Into::into),

            json_schema: self.json_schema.as_ref().and_then(|s| serde_json::from_str(s).ok()),

            error: self.error.clone().map(Into::into),

            extraction_duration_ms: self.extraction_duration_ms,

            category: self.category.clone(),

            tags: self.tags.clone(),

            document_version: self.document_version.clone(),

            abstract_text: self.abstract_text.clone(),

            output_format: self.output_format.clone(),

            ocr_used: self.ocr_used,

            additional: self
                .additional
                .clone()
                .into_iter()
                .map(|(k, v)| {
                    (
                        k.into(),
                        serde_json::from_str(&v).unwrap_or(serde_json::Value::String(v)),
                    )
                })
                .collect(),
        };
        core_self.is_empty()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ExcelMetadata {
    /// Number of sheets in the workbook.
    #[pyo3(get)]
    pub sheet_count: Option<u32>,
    /// Names of all sheets in the workbook.
    #[pyo3(get)]
    pub sheet_names: Option<Vec<String>>,
}

#[pymethods]
impl ExcelMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (sheet_count=None, sheet_names=None))]
    #[new]
    pub fn new(sheet_count: Option<u32>, sheet_names: Option<Vec<String>>) -> Self {
        Self {
            sheet_count,
            sheet_names,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct EmailMetadata {
    /// Sender's email address
    #[pyo3(get)]
    pub from_email: Option<String>,
    /// Sender's display name
    #[pyo3(get)]
    pub from_name: Option<String>,
    /// Primary recipients
    #[pyo3(get)]
    pub to_emails: Vec<String>,
    /// CC recipients
    #[pyo3(get)]
    pub cc_emails: Vec<String>,
    /// BCC recipients
    #[pyo3(get)]
    pub bcc_emails: Vec<String>,
    /// Message-ID header value
    #[pyo3(get)]
    pub message_id: Option<String>,
    /// List of attachment filenames
    #[pyo3(get)]
    pub attachments: Vec<String>,
}

#[pymethods]
impl EmailMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (to_emails=Self::default().to_emails, cc_emails=Self::default().cc_emails, bcc_emails=Self::default().bcc_emails, attachments=Self::default().attachments, from_email=None, from_name=None, message_id=None))]
    #[new]
    pub fn new(
        to_emails: Vec<String>,
        cc_emails: Vec<String>,
        bcc_emails: Vec<String>,
        attachments: Vec<String>,
        from_email: Option<String>,
        from_name: Option<String>,
        message_id: Option<String>,
    ) -> Self {
        Self {
            from_email,
            from_name,
            to_emails,
            cc_emails,
            bcc_emails,
            message_id,
            attachments,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ArchiveMetadata {
    /// Archive format ("ZIP", "TAR", "7Z", etc.)
    #[pyo3(get)]
    pub format: String,
    /// Total number of files in the archive
    #[pyo3(get)]
    pub file_count: u32,
    /// List of file paths within the archive
    #[pyo3(get)]
    pub file_list: Vec<String>,
    /// Total uncompressed size in bytes
    #[pyo3(get)]
    pub total_size: u64,
    /// Compressed size in bytes (if available)
    #[pyo3(get)]
    pub compressed_size: Option<u64>,
}

#[pymethods]
impl ArchiveMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (format=Self::default().format, file_count=Self::default().file_count, file_list=Self::default().file_list, total_size=Self::default().total_size, compressed_size=None))]
    #[new]
    pub fn new(
        format: String,
        file_count: u32,
        file_list: Vec<String>,
        total_size: u64,
        compressed_size: Option<u64>,
    ) -> Self {
        Self {
            format,
            file_count,
            file_list,
            total_size,
            compressed_size,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ImageMetadata {
    /// Image width in pixels
    #[pyo3(get)]
    pub width: u32,
    /// Image height in pixels
    #[pyo3(get)]
    pub height: u32,
    /// Image format (e.g., "PNG", "JPEG", "TIFF")
    #[pyo3(get)]
    pub format: String,
    /// EXIF metadata tags
    #[pyo3(get)]
    pub exif: HashMap<String, String>,
}

#[pymethods]
impl ImageMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (width=Self::default().width, height=Self::default().height, format=Self::default().format, exif=Self::default().exif))]
    #[new]
    pub fn new(width: u32, height: u32, format: String, exif: HashMap<String, String>) -> Self {
        Self {
            width,
            height,
            format,
            exif,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct XmlMetadata {
    /// Total number of XML elements processed
    #[pyo3(get)]
    pub element_count: u32,
    /// List of unique element tag names (sorted)
    #[pyo3(get)]
    pub unique_elements: Vec<String>,
}

#[pymethods]
impl XmlMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (element_count=Self::default().element_count, unique_elements=Self::default().unique_elements))]
    #[new]
    pub fn new(element_count: u32, unique_elements: Vec<String>) -> Self {
        Self {
            element_count,
            unique_elements,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct TextMetadata {
    /// Number of lines in the document
    #[pyo3(get)]
    pub line_count: u32,
    /// Number of words
    #[pyo3(get)]
    pub word_count: u32,
    /// Number of characters
    #[pyo3(get)]
    pub character_count: u32,
    /// Markdown headers (headings text only, for Markdown files)
    #[pyo3(get)]
    pub headers: Option<Vec<String>>,
    /// Markdown links as (text, url) tuples (for Markdown files)
    #[pyo3(get)]
    #[serde(skip)]
    pub links: Option<Vec<Vec<String>>>,
    /// Code blocks as (language, code) tuples (for Markdown files)
    #[pyo3(get)]
    #[serde(skip)]
    pub code_blocks: Option<Vec<Vec<String>>>,
}

#[pymethods]
impl TextMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (line_count=Self::default().line_count, word_count=Self::default().word_count, character_count=Self::default().character_count, headers=None, links=None, code_blocks=None))]
    #[new]
    pub fn new(
        line_count: u32,
        word_count: u32,
        character_count: u32,
        headers: Option<Vec<String>>,
        links: Option<Vec<Vec<String>>>,
        code_blocks: Option<Vec<Vec<String>>>,
    ) -> Self {
        Self {
            line_count,
            word_count,
            character_count,
            headers,
            links,
            code_blocks,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct HeaderMetadata {
    /// Header level: 1 (h1) through 6 (h6)
    #[pyo3(get)]
    pub level: u8,
    /// Normalized text content of the header
    #[pyo3(get)]
    pub text: String,
    /// HTML id attribute if present
    #[pyo3(get)]
    pub id: Option<String>,
    /// Document tree depth at the header element
    #[pyo3(get)]
    pub depth: u32,
    /// Byte offset in original HTML document
    #[pyo3(get)]
    pub html_offset: u32,
}

#[pymethods]
impl HeaderMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (level, text, depth, html_offset, id=None))]
    #[new]
    pub fn new(level: u8, text: String, depth: u32, html_offset: u32, id: Option<String>) -> Self {
        Self {
            level,
            text,
            id,
            depth,
            html_offset,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct LinkMetadata {
    /// The href URL value
    #[pyo3(get)]
    pub href: String,
    /// Link text content (normalized)
    #[pyo3(get)]
    pub text: String,
    /// Optional title attribute
    #[pyo3(get)]
    pub title: Option<String>,
    /// Link type classification
    #[pyo3(get)]
    pub link_type: LinkType,
    /// Rel attribute values
    #[pyo3(get)]
    pub rel: Vec<String>,
    /// Additional attributes as key-value pairs
    #[pyo3(get)]
    #[serde(skip)]
    pub attributes: Vec<Vec<String>>,
}

#[pymethods]
impl LinkMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (href, text, link_type, rel, attributes, title=None))]
    #[new]
    pub fn new(
        href: String,
        text: String,
        link_type: LinkType,
        rel: Vec<String>,
        attributes: Vec<Vec<String>>,
        title: Option<String>,
    ) -> Self {
        Self {
            href,
            text,
            title,
            link_type,
            rel,
            attributes,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ImageMetadataType {
    /// Image source (URL, data URI, or SVG content)
    #[pyo3(get)]
    pub src: String,
    /// Alternative text from alt attribute
    #[pyo3(get)]
    pub alt: Option<String>,
    /// Title attribute
    #[pyo3(get)]
    pub title: Option<String>,
    /// Image dimensions as (width, height) if available
    #[pyo3(get)]
    #[serde(skip)]
    pub dimensions: Option<Vec<u32>>,
    /// Image type classification
    #[pyo3(get)]
    pub image_type: ImageType,
    /// Additional attributes as key-value pairs
    #[pyo3(get)]
    #[serde(skip)]
    pub attributes: Vec<Vec<String>>,
}

#[pymethods]
impl ImageMetadataType {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (src, image_type, attributes, alt=None, title=None, dimensions=None))]
    #[new]
    pub fn new(
        src: String,
        image_type: ImageType,
        attributes: Vec<Vec<String>>,
        alt: Option<String>,
        title: Option<String>,
        dimensions: Option<Vec<u32>>,
    ) -> Self {
        Self {
            src,
            alt,
            title,
            dimensions,
            image_type,
            attributes,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct StructuredData {
    /// Type of structured data
    #[pyo3(get)]
    pub data_type: StructuredDataType,
    /// Raw JSON string representation
    #[pyo3(get)]
    pub raw_json: String,
    /// Schema type if detectable (e.g., "Article", "Event", "Product")
    #[pyo3(get)]
    pub schema_type: Option<String>,
}

#[pymethods]
impl StructuredData {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (data_type, raw_json, schema_type=None))]
    #[new]
    pub fn new(data_type: StructuredDataType, raw_json: String, schema_type: Option<String>) -> Self {
        Self {
            data_type,
            raw_json,
            schema_type,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct HtmlMetadata {
    /// Document title from `<title>` tag
    #[pyo3(get)]
    pub title: Option<String>,
    /// Document description from `<meta name="description">` tag
    #[pyo3(get)]
    pub description: Option<String>,
    /// Document keywords from `<meta name="keywords">` tag, split on commas
    #[pyo3(get)]
    pub keywords: Vec<String>,
    /// Document author from `<meta name="author">` tag
    #[pyo3(get)]
    pub author: Option<String>,
    /// Canonical URL from `<link rel="canonical">` tag
    #[pyo3(get)]
    pub canonical_url: Option<String>,
    /// Base URL from `<base href="">` tag for resolving relative URLs
    #[pyo3(get)]
    pub base_href: Option<String>,
    /// Document language from `lang` attribute
    #[pyo3(get)]
    pub language: Option<String>,
    /// Document text direction from `dir` attribute
    #[pyo3(get)]
    pub text_direction: Option<TextDirection>,
    /// Open Graph metadata (og:* properties) for social media
    /// Keys like "title", "description", "image", "url", etc.
    #[pyo3(get)]
    pub open_graph: HashMap<String, String>,
    /// Twitter Card metadata (twitter:* properties)
    /// Keys like "card", "site", "creator", "title", "description", "image", etc.
    #[pyo3(get)]
    pub twitter_card: HashMap<String, String>,
    /// Additional meta tags not covered by specific fields
    /// Keys are meta name/property attributes, values are content
    #[pyo3(get)]
    pub meta_tags: HashMap<String, String>,
    /// Extracted header elements with hierarchy
    #[pyo3(get)]
    pub headers: Vec<HeaderMetadata>,
    /// Extracted hyperlinks with type classification
    #[pyo3(get)]
    pub links: Vec<LinkMetadata>,
    /// Extracted images with source and dimensions
    #[pyo3(get)]
    pub images: Vec<ImageMetadataType>,
    /// Extracted structured data blocks
    #[pyo3(get)]
    pub structured_data: Vec<StructuredData>,
}

#[pymethods]
impl HtmlMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (keywords=Self::default().keywords, open_graph=Self::default().open_graph, twitter_card=Self::default().twitter_card, meta_tags=Self::default().meta_tags, headers=Self::default().headers, links=Self::default().links, images=Self::default().images, structured_data=Self::default().structured_data, title=None, description=None, author=None, canonical_url=None, base_href=None, language=None, text_direction=None))]
    #[new]
    pub fn new(
        keywords: Vec<String>,
        open_graph: HashMap<String, String>,
        twitter_card: HashMap<String, String>,
        meta_tags: HashMap<String, String>,
        headers: Vec<HeaderMetadata>,
        links: Vec<LinkMetadata>,
        images: Vec<ImageMetadataType>,
        structured_data: Vec<StructuredData>,
        title: Option<String>,
        description: Option<String>,
        author: Option<String>,
        canonical_url: Option<String>,
        base_href: Option<String>,
        language: Option<String>,
        text_direction: Option<TextDirection>,
    ) -> Self {
        Self {
            title,
            description,
            keywords,
            author,
            canonical_url,
            base_href,
            language,
            text_direction,
            open_graph,
            twitter_card,
            meta_tags,
            headers,
            links,
            images,
            structured_data,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct OcrMetadata {
    /// OCR language code(s) used
    #[pyo3(get)]
    pub language: String,
    /// Tesseract Page Segmentation Mode (PSM)
    #[pyo3(get)]
    pub psm: i32,
    /// Output format (e.g., "text", "hocr")
    #[pyo3(get)]
    pub output_format: String,
    /// Number of tables detected
    #[pyo3(get)]
    pub table_count: u32,
    #[pyo3(get)]
    pub table_rows: Option<u32>,
    #[pyo3(get)]
    pub table_cols: Option<u32>,
}

#[pymethods]
impl OcrMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (language=Self::default().language, psm=Self::default().psm, output_format=Self::default().output_format, table_count=Self::default().table_count, table_rows=None, table_cols=None))]
    #[new]
    pub fn new(
        language: String,
        psm: i32,
        output_format: String,
        table_count: u32,
        table_rows: Option<u32>,
        table_cols: Option<u32>,
    ) -> Self {
        Self {
            language,
            psm,
            output_format,
            table_count,
            table_rows,
            table_cols,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ErrorMetadata {
    #[pyo3(get)]
    pub error_type: String,
    #[pyo3(get)]
    pub message: String,
}

#[pymethods]
impl ErrorMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (error_type, message))]
    #[new]
    pub fn new(error_type: String, message: String) -> Self {
        Self { error_type, message }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PptxMetadata {
    /// Total number of slides in the presentation
    #[pyo3(get)]
    pub slide_count: u32,
    /// Names of slides (if available)
    #[pyo3(get)]
    pub slide_names: Vec<String>,
    /// Number of embedded images
    #[pyo3(get)]
    pub image_count: Option<u32>,
    /// Number of tables
    #[pyo3(get)]
    pub table_count: Option<u32>,
}

#[pymethods]
impl PptxMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (slide_count=Self::default().slide_count, slide_names=Self::default().slide_names, image_count=None, table_count=None))]
    #[new]
    pub fn new(slide_count: u32, slide_names: Vec<String>, image_count: Option<u32>, table_count: Option<u32>) -> Self {
        Self {
            slide_count,
            slide_names,
            image_count,
            table_count,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DocxMetadata {
    /// Core properties from docProps/core.xml (Dublin Core metadata)
    ///
    /// Contains title, creator, subject, keywords, dates, etc.
    /// Shared format across DOCX/PPTX/XLSX documents.
    #[pyo3(get)]
    pub core_properties: Option<CoreProperties>,
    /// Application properties from docProps/app.xml (Word-specific statistics)
    ///
    /// Contains word count, page count, paragraph count, editing time, etc.
    /// DOCX-specific variant of Office application properties.
    #[pyo3(get)]
    pub app_properties: Option<DocxAppProperties>,
    /// Custom properties from docProps/custom.xml (user-defined properties)
    ///
    /// Contains key-value pairs defined by users or applications.
    /// Values can be strings, numbers, booleans, or dates.
    #[pyo3(get)]
    pub custom_properties: Option<HashMap<String, String>>,
}

#[pymethods]
impl DocxMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (core_properties=None, app_properties=None, custom_properties=None))]
    #[new]
    pub fn new(
        core_properties: Option<CoreProperties>,
        app_properties: Option<DocxAppProperties>,
        custom_properties: Option<HashMap<String, String>>,
    ) -> Self {
        Self {
            core_properties,
            app_properties,
            custom_properties,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct CsvMetadata {
    #[pyo3(get)]
    pub row_count: u32,
    #[pyo3(get)]
    pub column_count: u32,
    #[pyo3(get)]
    pub delimiter: Option<String>,
    #[pyo3(get)]
    pub has_header: bool,
    #[pyo3(get)]
    pub column_types: Option<Vec<String>>,
}

#[pymethods]
impl CsvMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (row_count=Self::default().row_count, column_count=Self::default().column_count, has_header=Self::default().has_header, delimiter=None, column_types=None))]
    #[new]
    pub fn new(
        row_count: u32,
        column_count: u32,
        has_header: bool,
        delimiter: Option<String>,
        column_types: Option<Vec<String>>,
    ) -> Self {
        Self {
            row_count,
            column_count,
            delimiter,
            has_header,
            column_types,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct BibtexMetadata {
    /// Number of entries in the bibliography.
    #[pyo3(get)]
    pub entry_count: usize,
    #[pyo3(get)]
    pub citation_keys: Vec<String>,
    #[pyo3(get)]
    pub authors: Vec<String>,
    #[pyo3(get)]
    pub year_range: Option<YearRange>,
    #[pyo3(get)]
    pub entry_types: Option<HashMap<String, usize>>,
}

#[pymethods]
impl BibtexMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (entry_count=Self::default().entry_count, citation_keys=Self::default().citation_keys, authors=Self::default().authors, year_range=None, entry_types=None))]
    #[new]
    pub fn new(
        entry_count: usize,
        citation_keys: Vec<String>,
        authors: Vec<String>,
        year_range: Option<YearRange>,
        entry_types: Option<HashMap<String, usize>>,
    ) -> Self {
        Self {
            entry_count,
            citation_keys,
            authors,
            year_range,
            entry_types,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct CitationMetadata {
    #[pyo3(get)]
    pub citation_count: usize,
    #[pyo3(get)]
    pub format: Option<String>,
    #[pyo3(get)]
    pub authors: Vec<String>,
    #[pyo3(get)]
    pub year_range: Option<YearRange>,
    #[pyo3(get)]
    pub dois: Vec<String>,
    #[pyo3(get)]
    pub keywords: Vec<String>,
}

#[pymethods]
impl CitationMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (citation_count=Self::default().citation_count, authors=Self::default().authors, dois=Self::default().dois, keywords=Self::default().keywords, format=None, year_range=None))]
    #[new]
    pub fn new(
        citation_count: usize,
        authors: Vec<String>,
        dois: Vec<String>,
        keywords: Vec<String>,
        format: Option<String>,
        year_range: Option<YearRange>,
    ) -> Self {
        Self {
            citation_count,
            format,
            authors,
            year_range,
            dois,
            keywords,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct YearRange {
    #[pyo3(get)]
    pub min: Option<u32>,
    #[pyo3(get)]
    pub max: Option<u32>,
    #[pyo3(get)]
    pub years: Vec<u32>,
}

#[pymethods]
impl YearRange {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (years, min=None, max=None))]
    #[new]
    pub fn new(years: Vec<u32>, min: Option<u32>, max: Option<u32>) -> Self {
        Self { min, max, years }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct FictionBookMetadata {
    #[pyo3(get)]
    pub genres: Vec<String>,
    #[pyo3(get)]
    pub sequences: Vec<String>,
    #[pyo3(get)]
    pub annotation: Option<String>,
}

#[pymethods]
impl FictionBookMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (genres=Self::default().genres, sequences=Self::default().sequences, annotation=None))]
    #[new]
    pub fn new(genres: Vec<String>, sequences: Vec<String>, annotation: Option<String>) -> Self {
        Self {
            genres,
            sequences,
            annotation,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DbfMetadata {
    #[pyo3(get)]
    pub record_count: usize,
    #[pyo3(get)]
    pub field_count: usize,
    #[pyo3(get)]
    pub fields: Vec<DbfFieldInfo>,
}

#[pymethods]
impl DbfMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (record_count=Self::default().record_count, field_count=Self::default().field_count, fields=Self::default().fields))]
    #[new]
    pub fn new(record_count: usize, field_count: usize, fields: Vec<DbfFieldInfo>) -> Self {
        Self {
            record_count,
            field_count,
            fields,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DbfFieldInfo {
    #[pyo3(get)]
    pub name: String,
    #[pyo3(get)]
    pub field_type: String,
}

#[pymethods]
impl DbfFieldInfo {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (name, field_type))]
    #[new]
    pub fn new(name: String, field_type: String) -> Self {
        Self { name, field_type }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct JatsMetadata {
    #[pyo3(get)]
    pub copyright: Option<String>,
    #[pyo3(get)]
    pub license: Option<String>,
    #[pyo3(get)]
    pub history_dates: HashMap<String, String>,
    #[pyo3(get)]
    pub contributor_roles: Vec<ContributorRole>,
}

#[pymethods]
impl JatsMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (history_dates=Self::default().history_dates, contributor_roles=Self::default().contributor_roles, copyright=None, license=None))]
    #[new]
    pub fn new(
        history_dates: HashMap<String, String>,
        contributor_roles: Vec<ContributorRole>,
        copyright: Option<String>,
        license: Option<String>,
    ) -> Self {
        Self {
            copyright,
            license,
            history_dates,
            contributor_roles,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ContributorRole {
    #[pyo3(get)]
    pub name: String,
    #[pyo3(get)]
    pub role: Option<String>,
}

#[pymethods]
impl ContributorRole {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (name, role=None))]
    #[new]
    pub fn new(name: String, role: Option<String>) -> Self {
        Self { name, role }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct EpubMetadata {
    #[pyo3(get)]
    pub coverage: Option<String>,
    #[pyo3(get)]
    pub dc_format: Option<String>,
    #[pyo3(get)]
    pub relation: Option<String>,
    #[pyo3(get)]
    pub source: Option<String>,
    #[pyo3(get)]
    pub dc_type: Option<String>,
    #[pyo3(get)]
    pub cover_image: Option<String>,
}

#[pymethods]
impl EpubMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (coverage=None, dc_format=None, relation=None, source=None, dc_type=None, cover_image=None))]
    #[new]
    pub fn new(
        coverage: Option<String>,
        dc_format: Option<String>,
        relation: Option<String>,
        source: Option<String>,
        dc_type: Option<String>,
        cover_image: Option<String>,
    ) -> Self {
        Self {
            coverage,
            dc_format,
            relation,
            source,
            dc_type,
            cover_image,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PstMetadata {
    #[pyo3(get)]
    pub message_count: usize,
}

#[pymethods]
impl PstMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (message_count=Self::default().message_count))]
    #[new]
    pub fn new(message_count: usize) -> Self {
        Self { message_count }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OcrConfidence {
    /// Detection confidence: how confident the OCR engine is that text exists here.
    ///
    /// PaddleOCR provides this as `box_score`, Tesseract doesn't have a direct equivalent.
    /// Range: 0.0 to 1.0 (or None if not available).
    #[pyo3(get)]
    pub detection: Option<f64>,
    /// Recognition confidence: how confident about the text content.
    ///
    /// Range: 0.0 to 1.0.
    #[pyo3(get)]
    pub recognition: f64,
}

#[pymethods]
impl OcrConfidence {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (recognition=Self::default().recognition, detection=None))]
    #[new]
    pub fn new(recognition: f64, detection: Option<f64>) -> Self {
        Self { detection, recognition }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OcrRotation {
    /// Rotation angle in degrees (0, 90, 180, 270 for PaddleOCR).
    #[pyo3(get)]
    pub angle_degrees: f64,
    /// Confidence score for the rotation detection.
    #[pyo3(get)]
    pub confidence: Option<f64>,
}

#[pymethods]
impl OcrRotation {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (angle_degrees, confidence=None))]
    #[new]
    pub fn new(angle_degrees: f64, confidence: Option<f64>) -> Self {
        Self {
            angle_degrees,
            confidence,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OcrElement {
    /// The recognized text content.
    #[pyo3(get)]
    pub text: String,
    /// Bounding geometry (rectangle or quadrilateral).
    #[pyo3(get)]
    pub geometry: OcrBoundingGeometry,
    /// Confidence scores for detection and recognition.
    #[pyo3(get)]
    pub confidence: OcrConfidence,
    /// Hierarchical level (word, line, block, page).
    #[pyo3(get)]
    pub level: OcrElementLevel,
    /// Rotation information (if detected).
    #[pyo3(get)]
    pub rotation: Option<OcrRotation>,
    /// Page number (1-indexed).
    #[pyo3(get)]
    pub page_number: u32,
    /// Parent element ID for hierarchical relationships.
    ///
    /// Only used for Tesseract output which has word -> line -> block hierarchy.
    #[pyo3(get)]
    pub parent_id: Option<String>,
    /// Backend-specific metadata that doesn't fit the unified schema.
    #[pyo3(get)]
    pub backend_metadata: HashMap<String, String>,
}

#[pymethods]
impl OcrElement {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (text=Self::default().text, geometry=Self::default().geometry, confidence=None, level=Self::default().level, page_number=Self::default().page_number, backend_metadata=Self::default().backend_metadata, rotation=None, parent_id=None))]
    #[new]
    pub fn new(
        text: String,
        geometry: OcrBoundingGeometry,
        confidence: Option<OcrConfidence>,
        level: OcrElementLevel,
        page_number: u32,
        backend_metadata: HashMap<String, String>,
        rotation: Option<OcrRotation>,
        parent_id: Option<String>,
    ) -> Self {
        Self {
            text,
            geometry,
            confidence: confidence.unwrap_or_else(|| Self::default().confidence),
            level,
            rotation,
            page_number,
            parent_id,
            backend_metadata,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OcrElementConfig {
    /// Whether to include OCR elements in the extraction result.
    ///
    /// When true, the `ocr_elements` field in `ExtractionResult` will be populated.
    #[pyo3(get)]
    pub include_elements: bool,
    /// Minimum hierarchical level to include.
    ///
    /// Elements below this level (e.g., words when min_level is Line) will be excluded.
    #[pyo3(get)]
    pub min_level: OcrElementLevel,
    /// Minimum recognition confidence threshold (0.0-1.0).
    ///
    /// Elements with confidence below this threshold will be filtered out.
    #[pyo3(get)]
    pub min_confidence: f64,
    /// Whether to build hierarchical relationships between elements.
    ///
    /// When true, `parent_id` fields will be populated based on spatial containment.
    /// Only meaningful for Tesseract output.
    #[pyo3(get)]
    pub build_hierarchy: bool,
}

#[pymethods]
impl OcrElementConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (include_elements=Self::default().include_elements, min_level=Self::default().min_level, min_confidence=Self::default().min_confidence, build_hierarchy=Self::default().build_hierarchy))]
    #[new]
    pub fn new(include_elements: bool, min_level: OcrElementLevel, min_confidence: f64, build_hierarchy: bool) -> Self {
        Self {
            include_elements,
            min_level,
            min_confidence,
            build_hierarchy,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PageStructure {
    /// Total number of pages/slides/sheets
    #[pyo3(get)]
    pub total_count: u32,
    /// Type of paginated unit
    #[pyo3(get)]
    pub unit_type: PageUnitType,
    /// Character offset boundaries for each page
    ///
    /// Maps character ranges in the extracted content to page numbers.
    /// Used for chunk page range calculation.
    #[pyo3(get)]
    pub boundaries: Option<Vec<PageBoundary>>,
    /// Detailed per-page metadata (optional, only when needed)
    #[pyo3(get)]
    pub pages: Option<Vec<PageInfo>>,
}

#[pymethods]
impl PageStructure {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (total_count, unit_type, boundaries=None, pages=None))]
    #[new]
    pub fn new(
        total_count: u32,
        unit_type: PageUnitType,
        boundaries: Option<Vec<PageBoundary>>,
        pages: Option<Vec<PageInfo>>,
    ) -> Self {
        Self {
            total_count,
            unit_type,
            boundaries,
            pages,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PageBoundary {
    /// Byte offset where this page starts in the content string (UTF-8 valid boundary, inclusive)
    #[pyo3(get)]
    pub byte_start: usize,
    /// Byte offset where this page ends in the content string (UTF-8 valid boundary, exclusive)
    #[pyo3(get)]
    pub byte_end: usize,
    /// Page number (1-indexed)
    #[pyo3(get)]
    pub page_number: u32,
}

#[pymethods]
impl PageBoundary {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (byte_start, byte_end, page_number))]
    #[new]
    pub fn new(byte_start: usize, byte_end: usize, page_number: u32) -> Self {
        Self {
            byte_start,
            byte_end,
            page_number,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PageInfo {
    /// Page number (1-indexed)
    #[pyo3(get)]
    pub number: u32,
    /// Page title (usually for presentations)
    #[pyo3(get)]
    pub title: Option<String>,
    /// Dimensions in points (PDF) or pixels (images): (width, height)
    #[pyo3(get)]
    #[serde(skip)]
    pub dimensions: Option<Vec<f64>>,
    /// Number of images on this page
    #[pyo3(get)]
    pub image_count: Option<u32>,
    /// Number of tables on this page
    #[pyo3(get)]
    pub table_count: Option<u32>,
    /// Whether this page is hidden (e.g., in presentations)
    #[pyo3(get)]
    pub hidden: Option<bool>,
    /// Whether this page is blank (no meaningful text, no images, no tables)
    ///
    /// A page is considered blank if it has fewer than 3 non-whitespace characters
    /// and contains no tables or images. This is useful for filtering out empty pages
    /// in scanned documents or PDFs with blank separator pages.
    #[pyo3(get)]
    pub is_blank: Option<bool>,
    /// Whether this page contains non-trivial vector graphics (paths, shapes, curves)
    ///
    /// Indicates the presence of vector-drawn content such as charts, diagrams,
    /// or geometric shapes (e.g., from Adobe InDesign, LaTeX TikZ). These are
    /// invisible to `ExtractionResult.images` since they are not embedded as raster
    /// XObjects. Set to `true` when path count exceeds a heuristic threshold,
    /// signaling that downstream consumers may want to rasterize the page to
    /// capture this content.
    ///
    /// Only populated for PDFs; `None` for other document types.
    #[pyo3(get)]
    pub has_vector_graphics: bool,
}

#[pymethods]
impl PageInfo {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (number, has_vector_graphics, title=None, dimensions=None, image_count=None, table_count=None, hidden=None, is_blank=None))]
    #[new]
    pub fn new(
        number: u32,
        has_vector_graphics: bool,
        title: Option<String>,
        dimensions: Option<Vec<f64>>,
        image_count: Option<u32>,
        table_count: Option<u32>,
        hidden: Option<bool>,
        is_blank: Option<bool>,
    ) -> Self {
        Self {
            number,
            title,
            dimensions,
            image_count,
            table_count,
            hidden,
            is_blank,
            has_vector_graphics,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PageContent {
    /// Page number (1-indexed)
    #[pyo3(get)]
    pub page_number: u32,
    /// Text content for this page
    #[pyo3(get)]
    pub content: String,
    /// Tables found on this page (uses Arc for memory efficiency)
    ///
    /// Serializes as Vec<Table> for JSON compatibility while maintaining
    /// Arc semantics in-memory for zero-copy sharing.
    #[pyo3(get)]
    pub tables: Vec<Table>,
    /// Indices into `ExtractionResult.images` for images found on this page.
    ///
    /// Each value is a zero-based index into the top-level `images` collection.
    /// Only populated when `extract_images = true` in the extraction config.
    #[pyo3(get)]
    pub image_indices: Vec<u32>,
    /// Hierarchy information for the page (when hierarchy extraction is enabled)
    ///
    /// Contains text hierarchy levels (H1-H6) extracted from the page content.
    #[pyo3(get)]
    pub hierarchy: Option<PageHierarchy>,
    /// Whether this page is blank (no meaningful text content)
    ///
    /// Determined during extraction based on text content analysis.
    /// A page is blank if it has fewer than 3 non-whitespace characters
    /// and contains no tables or images.
    #[pyo3(get)]
    pub is_blank: Option<bool>,
    /// Layout detection regions for this page (when layout detection is enabled).
    ///
    /// Contains detected layout regions with class, confidence, bounding box,
    /// and area fraction. Only populated when layout detection is configured.
    #[pyo3(get)]
    pub layout_regions: Option<Vec<LayoutRegion>>,
    /// Speaker notes for this slide (PPTX only).
    ///
    /// Contains the text from the slide's notes pane (`ppt/notesSlides/notesSlide{N}.xml`).
    /// Only populated when the source is a PPTX file and notes are present.
    #[pyo3(get)]
    pub speaker_notes: Option<String>,
    /// Section name this slide belongs to (PPTX only).
    ///
    /// PowerPoint sections group slides into logical chapters (`<p:sectionLst>` in
    /// `ppt/presentation.xml`). Only populated when the source is a PPTX file and
    /// the slide belongs to a named section.
    #[pyo3(get)]
    pub section_name: Option<String>,
    /// Sheet name for this page (XLSX/ODS only).
    ///
    /// Each spreadsheet sheet maps to one `PageContent` entry. This field carries the
    /// sheet's display name as it appears in the workbook. `None` for all non-spreadsheet
    /// formats and for sheets with an empty name.
    #[pyo3(get)]
    pub sheet_name: Option<String>,
}

#[pymethods]
impl PageContent {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (page_number, content, tables, image_indices, hierarchy=None, is_blank=None, layout_regions=None, speaker_notes=None, section_name=None, sheet_name=None))]
    #[new]
    pub fn new(
        page_number: u32,
        content: String,
        tables: Vec<Table>,
        image_indices: Vec<u32>,
        hierarchy: Option<PageHierarchy>,
        is_blank: Option<bool>,
        layout_regions: Option<Vec<LayoutRegion>>,
        speaker_notes: Option<String>,
        section_name: Option<String>,
        sheet_name: Option<String>,
    ) -> Self {
        Self {
            page_number,
            content,
            tables,
            image_indices,
            hierarchy,
            is_blank,
            layout_regions,
            speaker_notes,
            section_name,
            sheet_name,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct LayoutRegion {
    /// Layout class name (e.g. "picture", "table", "text", "section_header").
    #[pyo3(get)]
    pub class_name: String,
    /// Confidence score from the layout detection model (0.0 to 1.0).
    #[pyo3(get)]
    pub confidence: f64,
    /// Bounding box in document coordinate space.
    #[pyo3(get)]
    pub bounding_box: BoundingBox,
    /// Fraction of the page area covered by this region (0.0 to 1.0).
    #[pyo3(get)]
    pub area_fraction: f64,
}

#[pymethods]
impl LayoutRegion {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (class_name=Self::default().class_name, confidence=Self::default().confidence, bounding_box=None, area_fraction=Self::default().area_fraction))]
    #[new]
    pub fn new(class_name: String, confidence: f64, bounding_box: Option<BoundingBox>, area_fraction: f64) -> Self {
        Self {
            class_name,
            confidence,
            bounding_box: bounding_box.unwrap_or_else(|| Self::default().bounding_box),
            area_fraction,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PageHierarchy {
    /// Number of hierarchy blocks on this page
    #[pyo3(get)]
    pub block_count: u32,
    /// Hierarchical blocks with heading levels
    #[pyo3(get)]
    pub blocks: Vec<HierarchicalBlock>,
}

#[pymethods]
impl PageHierarchy {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (block_count, blocks))]
    #[new]
    pub fn new(block_count: u32, blocks: Vec<HierarchicalBlock>) -> Self {
        Self { block_count, blocks }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct HierarchicalBlock {
    /// The text content of this block
    #[pyo3(get)]
    pub text: String,
    /// The font size of the text in this block
    #[pyo3(get)]
    pub font_size: f32,
    /// The hierarchy level of this block (H1-H6 or Body)
    ///
    /// Levels correspond to HTML heading tags:
    /// - "h1": Top-level heading
    /// - "h2": Secondary heading
    /// - "h3": Tertiary heading
    /// - "h4": Quaternary heading
    /// - "h5": Quinary heading
    /// - "h6": Senary heading
    /// - "body": Body text (no heading level)
    #[pyo3(get)]
    pub level: String,
    /// Bounding box information for the block
    ///
    /// Contains coordinates as (left, top, right, bottom) in PDF units.
    #[pyo3(get)]
    #[serde(skip)]
    pub bbox: Option<Vec<f32>>,
}

#[pymethods]
impl HierarchicalBlock {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (text, font_size, level, bbox=None))]
    #[new]
    pub fn new(text: String, font_size: f32, level: String, bbox: Option<Vec<f32>>) -> Self {
        Self {
            text,
            font_size,
            level,
            bbox,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct CellChange {
    /// Zero-based row index.
    #[pyo3(get)]
    pub row: usize,
    /// Zero-based column index.
    #[pyo3(get)]
    pub col: usize,
    /// Value before the change.
    #[pyo3(get, name = "from")]
    #[serde(rename = "from")]
    pub from_: String,
    /// Value after the change.
    #[pyo3(get)]
    pub to: String,
}

#[pymethods]
impl CellChange {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (row, col, from_, to))]
    #[new]
    pub fn new(row: usize, col: usize, from_: String, to: String) -> Self {
        Self { row, col, from_, to }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct DocumentRevision {
    /// Format-specific revision identifier.
    ///
    /// For DOCX this is the `w:id` attribute value on the change element
    /// (e.g. `"42"`). When the attribute is absent a synthetic fallback is
    /// generated (`"docx-ins-0"`, `"docx-del-3"`, …).
    #[pyo3(get)]
    pub revision_id: String,
    /// Display name of the author who made this change, when available.
    #[pyo3(get)]
    pub author: Option<String>,
    /// ISO-8601 timestamp of the change, when available.
    ///
    /// Stored as a plain string so this type remains FFI-friendly and
    /// unconditionally available without the `chrono` optional dep.
    /// DOCX populates this from the `w:date` attribute (e.g.
    /// `"2024-03-15T10:30:00Z"`).
    #[pyo3(get)]
    pub timestamp: Option<String>,
    /// Semantic kind of this revision.
    #[pyo3(get)]
    pub kind: RevisionKind,
    /// Best-effort document location for this revision.
    ///
    /// Resolution is format-dependent and may be `None` when the location
    /// cannot be determined (e.g. changes inside table cells before
    /// table-cell anchor support is added).
    #[pyo3(get)]
    pub anchor: Option<RevisionAnchor>,
    /// The content changes that make up this revision.
    #[pyo3(get)]
    #[serde(skip)]
    pub delta: RevisionDelta,
}

#[pymethods]
impl DocumentRevision {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (revision_id, kind, delta, author=None, timestamp=None, anchor=None))]
    #[new]
    pub fn new(
        revision_id: String,
        kind: RevisionKind,
        delta: RevisionDelta,
        author: Option<String>,
        timestamp: Option<String>,
        anchor: Option<RevisionAnchor>,
    ) -> Self {
        Self {
            revision_id,
            author,
            timestamp,
            kind,
            anchor,
            delta,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct RevisionDelta {
    /// Line-level content changes for this revision.
    #[pyo3(get)]
    pub content: Vec<DiffLine>,
    /// Cell-level table changes for this revision.
    #[pyo3(get)]
    pub table_changes: Vec<CellChange>,
}

#[pymethods]
impl RevisionDelta {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content=Self::default().content, table_changes=Self::default().table_changes))]
    #[new]
    pub fn new(content: Vec<DiffLine>, table_changes: Vec<CellChange>) -> Self {
        Self { content, table_changes }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct Table {
    /// Table cells as a 2D vector (rows × columns)
    #[pyo3(get)]
    pub cells: Vec<Vec<String>>,
    /// Markdown representation of the table
    #[pyo3(get)]
    pub markdown: String,
    /// Page number where the table was found (1-indexed)
    #[pyo3(get)]
    pub page_number: u32,
    /// Bounding box of the table on the page (PDF coordinates: x0=left, y0=bottom, x1=right, y1=top).
    /// Only populated for PDF-extracted tables when position data is available.
    #[pyo3(get)]
    pub bounding_box: Option<BoundingBox>,
}

#[pymethods]
impl Table {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (cells=Self::default().cells, markdown=Self::default().markdown, page_number=Self::default().page_number, bounding_box=None))]
    #[new]
    pub fn new(cells: Vec<Vec<String>>, markdown: String, page_number: u32, bounding_box: Option<BoundingBox>) -> Self {
        Self {
            cells,
            markdown,
            page_number,
            bounding_box,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct TableCell {
    /// Cell content as text
    #[pyo3(get)]
    pub content: String,
    /// Row span (number of rows this cell spans)
    #[pyo3(get)]
    pub row_span: u32,
    /// Column span (number of columns this cell spans)
    #[pyo3(get)]
    pub col_span: u32,
    /// Whether this is a header cell
    #[pyo3(get)]
    pub is_header: bool,
}

#[pymethods]
impl TableCell {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content=Self::default().content, row_span=Self::default().row_span, col_span=Self::default().col_span, is_header=Self::default().is_header))]
    #[new]
    pub fn new(content: String, row_span: u32, col_span: u32, is_header: bool) -> Self {
        Self {
            content,
            row_span,
            col_span,
            is_header,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ExtractedUri {
    /// The URL or path string.
    #[pyo3(get)]
    pub url: String,
    /// Optional display text / label for the link.
    #[pyo3(get)]
    pub label: Option<String>,
    /// Optional page number where the URI was found (1-indexed).
    #[pyo3(get)]
    pub page: Option<u32>,
    /// Semantic classification of the URI.
    #[pyo3(get)]
    pub kind: UriKind,
}

#[pymethods]
impl ExtractedUri {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (url, kind, label=None, page=None))]
    #[new]
    pub fn new(url: String, kind: UriKind, label: Option<String>, page: Option<u32>) -> Self {
        Self { url, label, page, kind }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DetectResponse {
    /// Detected MIME type
    #[pyo3(get)]
    pub mime_type: String,
    /// Original filename (if provided)
    #[pyo3(get)]
    pub filename: Option<String>,
}

#[pymethods]
impl DetectResponse {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (mime_type, filename=None))]
    #[new]
    pub fn new(mime_type: String, filename: Option<String>) -> Self {
        Self { mime_type, filename }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DiffOptions {
    /// Include metadata changes in the diff. Default: `true`.
    #[pyo3(get)]
    pub include_metadata: bool,
    /// Include embedded-children changes in the diff. Default: `true`.
    #[pyo3(get)]
    pub include_embedded: bool,
    /// Truncate content to this many characters before diffing.
    ///
    /// Useful for very large documents where only the first N characters matter.
    /// `None` means no truncation.
    #[pyo3(get)]
    pub max_content_chars: Option<usize>,
}

#[pymethods]
impl DiffOptions {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (include_metadata=Self::default().include_metadata, include_embedded=Self::default().include_embedded, max_content_chars=None))]
    #[new]
    pub fn new(include_metadata: bool, include_embedded: bool, max_content_chars: Option<usize>) -> Self {
        Self {
            include_metadata,
            include_embedded,
            max_content_chars,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> DiffOptions {
        kreuzberg::DiffOptions::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct ExtractionDiff {
    /// Unified-diff hunks for the `content` field.
    ///
    /// Empty when the content is identical.
    #[pyo3(get)]
    #[serde(skip)]
    pub content_diff: Vec<DiffHunk>,
    /// Tables present in `b` but not in `a` (by index position, excess right-side tables).
    #[pyo3(get)]
    pub tables_added: Vec<Table>,
    /// Tables present in `a` but not in `b` (by index position, excess left-side tables).
    #[pyo3(get)]
    pub tables_removed: Vec<Table>,
    /// Cell-level changes for table pairs that share the same index and dimensions.
    #[pyo3(get)]
    pub tables_changed: Vec<TableDiff>,
    /// Metadata difference, encoded as a JSON object with three top-level keys:
    /// `added` (keys present in `b` but not `a`), `removed` (keys present in `a`
    /// but not `b`), and `changed` (keys whose values differ — each entry is
    /// `{ "from": <value-in-a>, "to": <value-in-b> }`).
    ///
    /// This is NOT RFC 6902 JSON Patch — we deliberately chose a flatter shape
    /// to avoid pulling in a json-patch crate. If you need RFC 6902 semantics
    /// (with JSON Pointer paths) feed `a.metadata` and `b.metadata` to your
    /// preferred json-patch impl directly.
    #[pyo3(get)]
    #[serde(default, deserialize_with = "alef_json_str::deserialize")]
    pub metadata_changed: String,
    /// Changes to embedded archive children.
    #[pyo3(get)]
    #[serde(skip)]
    pub embedded_changes: EmbeddedChanges,
}

#[pymethods]
impl ExtractionDiff {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (content_diff, tables_added, tables_removed, tables_changed, metadata_changed, embedded_changes))]
    #[new]
    pub fn new(
        content_diff: Vec<DiffHunk>,
        tables_added: Vec<Table>,
        tables_removed: Vec<Table>,
        tables_changed: Vec<TableDiff>,
        metadata_changed: String,
        embedded_changes: EmbeddedChanges,
    ) -> Self {
        Self {
            content_diff,
            tables_added,
            tables_removed,
            tables_changed,
            metadata_changed,
            embedded_changes,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DiffHunk {
    /// Starting line number in the old content (0-indexed).
    #[pyo3(get)]
    pub from_line: usize,
    /// Number of lines from the old content in this hunk.
    #[pyo3(get)]
    pub from_count: usize,
    /// Starting line number in the new content (0-indexed).
    #[pyo3(get)]
    pub to_line: usize,
    /// Number of lines from the new content in this hunk.
    #[pyo3(get)]
    pub to_count: usize,
    /// Lines that make up this hunk.
    #[pyo3(get)]
    pub lines: Vec<DiffLine>,
}

#[pymethods]
impl DiffHunk {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (from_line, from_count, to_line, to_count, lines))]
    #[new]
    pub fn new(from_line: usize, from_count: usize, to_line: usize, to_count: usize, lines: Vec<DiffLine>) -> Self {
        Self {
            from_line,
            from_count,
            to_line,
            to_count,
            lines,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct TableDiff {
    /// Zero-based index of the table in both `a.tables` and `b.tables`.
    #[pyo3(get)]
    pub from_index: usize,
    /// Zero-based index in `b.tables` (equal to `from_index` for same-dimension tables).
    #[pyo3(get)]
    pub to_index: usize,
    /// Cell-level changes within the table.
    #[pyo3(get)]
    pub cell_changes: Vec<CellChange>,
}

#[pymethods]
impl TableDiff {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (from_index, to_index, cell_changes))]
    #[new]
    pub fn new(from_index: usize, to_index: usize, cell_changes: Vec<CellChange>) -> Self {
        Self {
            from_index,
            to_index,
            cell_changes,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct EmbeddedChanges {
    /// Children present in `b` but not in `a` (matched by `path`).
    #[pyo3(get)]
    #[serde(skip)]
    pub added: Vec<ArchiveEntry>,
    /// Children present in `a` but not in `b` (matched by `path`).
    #[pyo3(get)]
    #[serde(skip)]
    pub removed: Vec<ArchiveEntry>,
    /// Children present in both but with differing content (matched by `path`).
    ///
    /// Each entry holds the diff of the nested `ExtractionResult`.
    #[pyo3(get)]
    #[serde(skip)]
    pub changed: Vec<EmbeddedDiff>,
}

#[pymethods]
impl EmbeddedChanges {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (added, removed, changed))]
    #[new]
    pub fn new(added: Vec<ArchiveEntry>, removed: Vec<ArchiveEntry>, changed: Vec<EmbeddedDiff>) -> Self {
        Self {
            added,
            removed,
            changed,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct EmbeddedDiff {
    /// Archive-relative path identifying this entry.
    #[pyo3(get)]
    pub path: String,
    /// The recursive diff of the entry's extraction result.
    #[pyo3(get)]
    #[serde(skip)]
    pub diff: ExtractionDiff,
}

#[pymethods]
impl EmbeddedDiff {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (path, diff))]
    #[new]
    pub fn new(path: String, diff: ExtractionDiff) -> Self {
        Self { path, diff }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct EmbeddingPreset {
    #[pyo3(get)]
    pub name: String,
    #[pyo3(get)]
    pub chunk_size: usize,
    #[pyo3(get)]
    pub overlap: usize,
    /// HuggingFace repository name for the model.
    #[pyo3(get)]
    pub model_repo: String,
    /// Pooling strategy: "cls" or "mean".
    #[pyo3(get)]
    pub pooling: String,
    /// Path to the ONNX model file within the repo.
    #[pyo3(get)]
    pub model_file: String,
    #[pyo3(get)]
    pub dimensions: usize,
    #[pyo3(get)]
    pub description: String,
}

#[pymethods]
impl EmbeddingPreset {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (name, chunk_size, overlap, model_repo, pooling, model_file, dimensions, description))]
    #[new]
    pub fn new(
        name: String,
        chunk_size: usize,
        overlap: usize,
        model_repo: String,
        pooling: String,
        model_file: String,
        dimensions: usize,
        description: String,
    ) -> Self {
        Self {
            name,
            chunk_size,
            overlap,
            model_repo,
            pooling,
            model_file,
            dimensions,
            description,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct YakeParams {
    /// Window size for co-occurrence analysis (default: 2).
    ///
    /// Controls the context window for computing co-occurrence statistics.
    #[pyo3(get)]
    pub window_size: usize,
}

#[pymethods]
impl YakeParams {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (window_size=Self::default().window_size))]
    #[new]
    pub fn new(window_size: usize) -> Self {
        Self { window_size }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> YakeParams {
        kreuzberg::YakeParams::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct RakeParams {
    /// Minimum word length to consider (default: 1).
    #[pyo3(get)]
    pub min_word_length: usize,
    /// Maximum words in a keyword phrase (default: 3).
    #[pyo3(get)]
    pub max_words_per_phrase: usize,
}

#[pymethods]
impl RakeParams {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (min_word_length=Self::default().min_word_length, max_words_per_phrase=Self::default().max_words_per_phrase))]
    #[new]
    pub fn new(min_word_length: usize, max_words_per_phrase: usize) -> Self {
        Self {
            min_word_length,
            max_words_per_phrase,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> RakeParams {
        kreuzberg::RakeParams::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct KeywordConfig {
    /// Algorithm to use for extraction.
    #[pyo3(get)]
    pub algorithm: KeywordAlgorithm,
    /// Maximum number of keywords to extract (default: 10).
    #[pyo3(get)]
    pub max_keywords: usize,
    /// Minimum score threshold (0.0-1.0, default: 0.0).
    ///
    /// Keywords with scores below this threshold are filtered out.
    /// Note: Score ranges differ between algorithms.
    #[pyo3(get)]
    pub min_score: f32,
    /// N-gram range for keyword extraction (min, max).
    ///
    /// (1, 1) = unigrams only
    /// (1, 2) = unigrams and bigrams
    /// (1, 3) = unigrams, bigrams, and trigrams (default)
    #[pyo3(get)]
    #[serde(skip)]
    pub ngram_range: Vec<usize>,
    /// Language code for stopword filtering (e.g., "en", "de", "fr").
    ///
    /// If None, no stopword filtering is applied.
    #[pyo3(get)]
    pub language: Option<String>,
    /// YAKE-specific tuning parameters.
    #[pyo3(get)]
    pub yake_params: Option<YakeParams>,
    /// RAKE-specific tuning parameters.
    #[pyo3(get)]
    pub rake_params: Option<RakeParams>,
}

#[pymethods]
impl KeywordConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (algorithm=Self::default().algorithm, max_keywords=Self::default().max_keywords, min_score=Self::default().min_score, ngram_range=Self::default().ngram_range, language=None, yake_params=None, rake_params=None))]
    #[new]
    pub fn new(
        algorithm: KeywordAlgorithm,
        max_keywords: usize,
        min_score: f32,
        ngram_range: Vec<usize>,
        language: Option<String>,
        yake_params: Option<YakeParams>,
        rake_params: Option<RakeParams>,
    ) -> Self {
        Self {
            algorithm,
            max_keywords,
            min_score,
            ngram_range,
            language,
            yake_params,
            rake_params,
        }
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> KeywordConfig {
        kreuzberg::KeywordConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct Keyword {
    /// The keyword text.
    #[pyo3(get)]
    pub text: String,
    /// Relevance score (higher is better, algorithm-specific range).
    #[pyo3(get)]
    pub score: f32,
    /// Algorithm that extracted this keyword.
    #[pyo3(get)]
    pub algorithm: KeywordAlgorithm,
    /// Optional positions where keyword appears in text (character offsets).
    #[pyo3(get)]
    pub positions: Option<Vec<usize>>,
}

#[pymethods]
impl Keyword {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (text, score, algorithm, positions=None))]
    #[new]
    pub fn new(text: String, score: f32, algorithm: KeywordAlgorithm, positions: Option<Vec<usize>>) -> Self {
        Self {
            text,
            score,
            algorithm,
            positions,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PaddleOcrConfig {
    /// Language code (e.g., "en", "ch", "jpn", "kor", "deu", "fra")
    #[pyo3(get)]
    pub language: String,
    /// Optional custom cache directory for model files
    #[pyo3(get)]
    pub cache_dir: Option<String>,
    /// Enable angle classification for rotated text (default: false).
    /// Can misfire on short text regions, rotating crops incorrectly before recognition.
    #[pyo3(get)]
    pub use_angle_cls: bool,
    /// Enable table structure detection (default: false)
    #[pyo3(get)]
    pub enable_table_detection: bool,
    /// Database threshold for text detection (default: 0.3)
    /// Range: 0.0-1.0, higher values require more confident detections
    #[pyo3(get)]
    pub det_db_thresh: f32,
    /// Box threshold for text bounding box refinement (default: 0.5)
    /// Range: 0.0-1.0
    #[pyo3(get)]
    pub det_db_box_thresh: f32,
    /// Unclip ratio for expanding text bounding boxes (default: 1.6)
    /// Controls the expansion of detected text regions
    #[pyo3(get)]
    pub det_db_unclip_ratio: f32,
    /// Maximum side length for detection image (default: 960)
    /// Larger images may be resized to this limit for faster inference
    #[pyo3(get)]
    pub det_limit_side_len: u32,
    /// Batch size for recognition inference (default: 6)
    /// Number of text regions to process simultaneously
    #[pyo3(get)]
    pub rec_batch_num: u32,
    /// Padding in pixels added around the image before detection (default: 10).
    /// Large values can include surrounding content like table gridlines.
    #[pyo3(get)]
    pub padding: u32,
    /// Minimum recognition confidence score for text lines (default: 0.5).
    /// Text regions with recognition confidence below this threshold are discarded.
    /// Matches PaddleOCR Python's `drop_score` parameter.
    /// Range: 0.0-1.0
    #[pyo3(get)]
    pub drop_score: f32,
    /// Model tier controlling detection/recognition model size and accuracy trade-off.
    /// - `"mobile"` (default): Lightweight models (~4.5MB detection, ~16.5MB recognition), fast download and inference
    /// - `"server"`: Large, high-accuracy models (~88MB detection, ~84MB recognition), best for GPU or complex documents
    #[pyo3(get)]
    pub model_tier: String,
}

#[pymethods]
impl PaddleOcrConfig {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (language=Self::default().language, use_angle_cls=Self::default().use_angle_cls, enable_table_detection=Self::default().enable_table_detection, det_db_thresh=Self::default().det_db_thresh, det_db_box_thresh=Self::default().det_db_box_thresh, det_db_unclip_ratio=Self::default().det_db_unclip_ratio, det_limit_side_len=Self::default().det_limit_side_len, rec_batch_num=Self::default().rec_batch_num, padding=Self::default().padding, drop_score=Self::default().drop_score, model_tier=Self::default().model_tier, cache_dir=None))]
    #[new]
    pub fn new(
        language: String,
        use_angle_cls: bool,
        enable_table_detection: bool,
        det_db_thresh: f32,
        det_db_box_thresh: f32,
        det_db_unclip_ratio: f32,
        det_limit_side_len: u32,
        rec_batch_num: u32,
        padding: u32,
        drop_score: f32,
        model_tier: String,
        cache_dir: Option<String>,
    ) -> Self {
        Self {
            language,
            cache_dir,
            use_angle_cls,
            enable_table_detection,
            det_db_thresh,
            det_db_box_thresh,
            det_db_unclip_ratio,
            det_limit_side_len,
            rec_batch_num,
            padding,
            drop_score,
            model_tier,
        }
    }

    #[pyo3(signature = (path))]
    pub fn with_cache_dir(&self, path: String) -> PaddleOcrConfig {
        let core_self = kreuzberg::PaddleOcrConfig {
            language: self.language.clone(),

            cache_dir: self.cache_dir.clone().map(Into::into),

            use_angle_cls: self.use_angle_cls,

            enable_table_detection: self.enable_table_detection,

            det_db_thresh: self.det_db_thresh,

            det_db_box_thresh: self.det_db_box_thresh,

            det_db_unclip_ratio: self.det_db_unclip_ratio,

            det_limit_side_len: self.det_limit_side_len,

            rec_batch_num: self.rec_batch_num,

            padding: self.padding,

            drop_score: self.drop_score,

            model_tier: self.model_tier.clone(),
        };
        core_self.with_cache_dir(std::path::PathBuf::from(path)).into()
    }

    #[pyo3(signature = (enable))]
    pub fn with_table_detection(&self, enable: bool) -> PaddleOcrConfig {
        let core_self = kreuzberg::PaddleOcrConfig {
            language: self.language.clone(),

            cache_dir: self.cache_dir.clone().map(Into::into),

            use_angle_cls: self.use_angle_cls,

            enable_table_detection: self.enable_table_detection,

            det_db_thresh: self.det_db_thresh,

            det_db_box_thresh: self.det_db_box_thresh,

            det_db_unclip_ratio: self.det_db_unclip_ratio,

            det_limit_side_len: self.det_limit_side_len,

            rec_batch_num: self.rec_batch_num,

            padding: self.padding,

            drop_score: self.drop_score,

            model_tier: self.model_tier.clone(),
        };
        core_self.with_table_detection(enable).into()
    }

    #[pyo3(signature = (enable))]
    pub fn with_angle_cls(&self, enable: bool) -> PaddleOcrConfig {
        let core_self = kreuzberg::PaddleOcrConfig {
            language: self.language.clone(),

            cache_dir: self.cache_dir.clone().map(Into::into),

            use_angle_cls: self.use_angle_cls,

            enable_table_detection: self.enable_table_detection,

            det_db_thresh: self.det_db_thresh,

            det_db_box_thresh: self.det_db_box_thresh,

            det_db_unclip_ratio: self.det_db_unclip_ratio,

            det_limit_side_len: self.det_limit_side_len,

            rec_batch_num: self.rec_batch_num,

            padding: self.padding,

            drop_score: self.drop_score,

            model_tier: self.model_tier.clone(),
        };
        core_self.with_angle_cls(enable).into()
    }

    #[pyo3(signature = (threshold))]
    pub fn with_det_db_thresh(&self, threshold: f32) -> PaddleOcrConfig {
        let core_self = kreuzberg::PaddleOcrConfig {
            language: self.language.clone(),

            cache_dir: self.cache_dir.clone().map(Into::into),

            use_angle_cls: self.use_angle_cls,

            enable_table_detection: self.enable_table_detection,

            det_db_thresh: self.det_db_thresh,

            det_db_box_thresh: self.det_db_box_thresh,

            det_db_unclip_ratio: self.det_db_unclip_ratio,

            det_limit_side_len: self.det_limit_side_len,

            rec_batch_num: self.rec_batch_num,

            padding: self.padding,

            drop_score: self.drop_score,

            model_tier: self.model_tier.clone(),
        };
        core_self.with_det_db_thresh(threshold).into()
    }

    #[pyo3(signature = (threshold))]
    pub fn with_det_db_box_thresh(&self, threshold: f32) -> PaddleOcrConfig {
        let core_self = kreuzberg::PaddleOcrConfig {
            language: self.language.clone(),

            cache_dir: self.cache_dir.clone().map(Into::into),

            use_angle_cls: self.use_angle_cls,

            enable_table_detection: self.enable_table_detection,

            det_db_thresh: self.det_db_thresh,

            det_db_box_thresh: self.det_db_box_thresh,

            det_db_unclip_ratio: self.det_db_unclip_ratio,

            det_limit_side_len: self.det_limit_side_len,

            rec_batch_num: self.rec_batch_num,

            padding: self.padding,

            drop_score: self.drop_score,

            model_tier: self.model_tier.clone(),
        };
        core_self.with_det_db_box_thresh(threshold).into()
    }

    #[pyo3(signature = (ratio))]
    pub fn with_det_db_unclip_ratio(&self, ratio: f32) -> PaddleOcrConfig {
        let core_self = kreuzberg::PaddleOcrConfig {
            language: self.language.clone(),

            cache_dir: self.cache_dir.clone().map(Into::into),

            use_angle_cls: self.use_angle_cls,

            enable_table_detection: self.enable_table_detection,

            det_db_thresh: self.det_db_thresh,

            det_db_box_thresh: self.det_db_box_thresh,

            det_db_unclip_ratio: self.det_db_unclip_ratio,

            det_limit_side_len: self.det_limit_side_len,

            rec_batch_num: self.rec_batch_num,

            padding: self.padding,

            drop_score: self.drop_score,

            model_tier: self.model_tier.clone(),
        };
        core_self.with_det_db_unclip_ratio(ratio).into()
    }

    #[pyo3(signature = (length))]
    pub fn with_det_limit_side_len(&self, length: u32) -> PaddleOcrConfig {
        let core_self = kreuzberg::PaddleOcrConfig {
            language: self.language.clone(),

            cache_dir: self.cache_dir.clone().map(Into::into),

            use_angle_cls: self.use_angle_cls,

            enable_table_detection: self.enable_table_detection,

            det_db_thresh: self.det_db_thresh,

            det_db_box_thresh: self.det_db_box_thresh,

            det_db_unclip_ratio: self.det_db_unclip_ratio,

            det_limit_side_len: self.det_limit_side_len,

            rec_batch_num: self.rec_batch_num,

            padding: self.padding,

            drop_score: self.drop_score,

            model_tier: self.model_tier.clone(),
        };
        core_self.with_det_limit_side_len(length).into()
    }

    #[pyo3(signature = (batch_size))]
    pub fn with_rec_batch_num(&self, batch_size: u32) -> PaddleOcrConfig {
        let core_self = kreuzberg::PaddleOcrConfig {
            language: self.language.clone(),

            cache_dir: self.cache_dir.clone().map(Into::into),

            use_angle_cls: self.use_angle_cls,

            enable_table_detection: self.enable_table_detection,

            det_db_thresh: self.det_db_thresh,

            det_db_box_thresh: self.det_db_box_thresh,

            det_db_unclip_ratio: self.det_db_unclip_ratio,

            det_limit_side_len: self.det_limit_side_len,

            rec_batch_num: self.rec_batch_num,

            padding: self.padding,

            drop_score: self.drop_score,

            model_tier: self.model_tier.clone(),
        };
        core_self.with_rec_batch_num(batch_size).into()
    }

    #[pyo3(signature = (score))]
    pub fn with_drop_score(&self, score: f32) -> PaddleOcrConfig {
        let core_self = kreuzberg::PaddleOcrConfig {
            language: self.language.clone(),

            cache_dir: self.cache_dir.clone().map(Into::into),

            use_angle_cls: self.use_angle_cls,

            enable_table_detection: self.enable_table_detection,

            det_db_thresh: self.det_db_thresh,

            det_db_box_thresh: self.det_db_box_thresh,

            det_db_unclip_ratio: self.det_db_unclip_ratio,

            det_limit_side_len: self.det_limit_side_len,

            rec_batch_num: self.rec_batch_num,

            padding: self.padding,

            drop_score: self.drop_score,

            model_tier: self.model_tier.clone(),
        };
        core_self.with_drop_score(score).into()
    }

    #[pyo3(signature = (padding))]
    pub fn with_padding(&self, padding: u32) -> PaddleOcrConfig {
        let core_self = kreuzberg::PaddleOcrConfig {
            language: self.language.clone(),

            cache_dir: self.cache_dir.clone().map(Into::into),

            use_angle_cls: self.use_angle_cls,

            enable_table_detection: self.enable_table_detection,

            det_db_thresh: self.det_db_thresh,

            det_db_box_thresh: self.det_db_box_thresh,

            det_db_unclip_ratio: self.det_db_unclip_ratio,

            det_limit_side_len: self.det_limit_side_len,

            rec_batch_num: self.rec_batch_num,

            padding: self.padding,

            drop_score: self.drop_score,

            model_tier: self.model_tier.clone(),
        };
        core_self.with_padding(padding).into()
    }

    #[pyo3(signature = (tier))]
    pub fn with_model_tier(&self, tier: String) -> PaddleOcrConfig {
        let core_self = kreuzberg::PaddleOcrConfig {
            language: self.language.clone(),

            cache_dir: self.cache_dir.clone().map(Into::into),

            use_angle_cls: self.use_angle_cls,

            enable_table_detection: self.enable_table_detection,

            det_db_thresh: self.det_db_thresh,

            det_db_box_thresh: self.det_db_box_thresh,

            det_db_unclip_ratio: self.det_db_unclip_ratio,

            det_limit_side_len: self.det_limit_side_len,

            rec_batch_num: self.rec_batch_num,

            padding: self.padding,

            drop_score: self.drop_score,

            model_tier: self.model_tier.clone(),
        };
        core_self.with_model_tier(tier).into()
    }

    #[allow(clippy::should_implement_trait)]
    #[staticmethod]
    #[pyo3(signature = ())]
    pub fn default() -> PaddleOcrConfig {
        kreuzberg::PaddleOcrConfig::default().into()
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct ModelPaths {
    /// Path to the detection model directory.
    #[pyo3(get)]
    pub det_model: String,
    /// Path to the classification model directory.
    #[pyo3(get)]
    pub cls_model: String,
    /// Path to the recognition model directory.
    #[pyo3(get)]
    pub rec_model: String,
    /// Path to the character dictionary file.
    #[pyo3(get)]
    pub dict_file: String,
}

#[pymethods]
impl ModelPaths {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (det_model, cls_model, rec_model, dict_file))]
    #[new]
    pub fn new(det_model: String, cls_model: String, rec_model: String, dict_file: String) -> Self {
        Self {
            det_model,
            cls_model,
            rec_model,
            dict_file,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct OrientationResult {
    /// Detected orientation in degrees (0, 90, 180, or 270).
    #[pyo3(get)]
    pub degrees: u32,
    /// Confidence score (0.0-1.0).
    #[pyo3(get)]
    pub confidence: f32,
}

#[pymethods]
impl OrientationResult {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (degrees, confidence))]
    #[new]
    pub fn new(degrees: u32, confidence: f32) -> Self {
        Self { degrees, confidence }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
#[allow(clippy::similar_names)]
pub struct BBox {
    #[pyo3(get)]
    pub x1: f32,
    #[pyo3(get)]
    pub y1: f32,
    #[pyo3(get)]
    pub x2: f32,
    #[pyo3(get)]
    pub y2: f32,
}

#[pymethods]
impl BBox {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (x1, y1, x2, y2))]
    #[new]
    pub fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
        Self { x1, y1, x2, y2 }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct LayoutDetection {
    #[pyo3(get)]
    pub class_name: LayoutClass,
    #[pyo3(get)]
    pub confidence: f32,
    #[pyo3(get)]
    pub bbox: BBox,
}

#[pymethods]
impl LayoutDetection {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (class_name, confidence, bbox))]
    #[new]
    pub fn new(class_name: LayoutClass, confidence: f32, bbox: BBox) -> Self {
        Self {
            class_name,
            confidence,
            bbox,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct RecognizedTable {
    /// Detection bbox that this table corresponds to (for matching).
    #[pyo3(get)]
    pub detection_bbox: BBox,
    /// Table cells as a 2D vector (rows × columns).
    #[pyo3(get)]
    pub cells: Vec<Vec<String>>,
    /// Rendered markdown table.
    #[pyo3(get)]
    pub markdown: String,
}

#[pymethods]
impl RecognizedTable {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (detection_bbox, cells, markdown))]
    #[new]
    pub fn new(detection_bbox: BBox, cells: Vec<Vec<String>>, markdown: String) -> Self {
        Self {
            detection_bbox,
            cells,
            markdown,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct DetectionResult {
    #[pyo3(get)]
    pub page_width: u32,
    #[pyo3(get)]
    pub page_height: u32,
    #[pyo3(get)]
    pub detections: Vec<LayoutDetection>,
}

#[pymethods]
impl DetectionResult {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (page_width, page_height, detections))]
    #[new]
    pub fn new(page_width: u32, page_height: u32, detections: Vec<LayoutDetection>) -> Self {
        Self {
            page_width,
            page_height,
            detections,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct EmbeddedFile {
    /// The filename as stored in the PDF name tree.
    #[pyo3(get)]
    pub name: String,
    /// Raw file bytes from the embedded stream (already decompressed by lopdf).
    #[pyo3(get)]
    pub data: Vec<u8>,
    /// Compressed byte count of the original stream (before decompression).
    ///
    /// Used by callers to compute the decompression ratio and detect zip-bomb-style
    /// attacks that embed a tiny compressed stream expanding to gigabytes of data.
    #[pyo3(get)]
    pub compressed_size: usize,
    /// MIME type if specified in the filespec, otherwise `None`.
    #[pyo3(get)]
    pub mime_type: Option<String>,
}

#[pymethods]
impl EmbeddedFile {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (name, data, compressed_size, mime_type=None))]
    #[new]
    pub fn new(name: String, data: Vec<u8>, compressed_size: usize, mime_type: Option<String>) -> Self {
        Self {
            name,
            data,
            compressed_size,
            mime_type,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(frozen, from_py_object)]
pub struct PdfMetadata {
    /// PDF version (e.g., "1.7", "2.0")
    #[pyo3(get)]
    pub pdf_version: Option<String>,
    /// PDF producer (application that created the PDF)
    #[pyo3(get)]
    pub producer: Option<String>,
    /// Whether the PDF is encrypted/password-protected
    #[pyo3(get)]
    pub is_encrypted: Option<bool>,
    /// First page width in points (1/72 inch)
    #[pyo3(get)]
    pub width: Option<i64>,
    /// First page height in points (1/72 inch)
    #[pyo3(get)]
    pub height: Option<i64>,
    /// Total number of pages in the PDF document
    #[pyo3(get)]
    pub page_count: Option<u32>,
}

#[pymethods]
impl PdfMetadata {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    #[pyo3(signature = (pdf_version=None, producer=None, is_encrypted=None, width=None, height=None, page_count=None))]
    #[new]
    pub fn new(
        pdf_version: Option<String>,
        producer: Option<String>,
        is_encrypted: Option<bool>,
        width: Option<i64>,
        height: Option<i64>,
        page_count: Option<u32>,
    ) -> Self {
        Self {
            pdf_version,
            producer,
            is_encrypted,
            width,
            height,
            page_count,
        }
    }

    #[staticmethod]
    fn from_json(json_str: String) -> pyo3::PyResult<Self> {
        serde_json::from_str::<Self>(&json_str).map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ExecutionProviderType {
    #[pyo3(name = "AUTO")]
    #[default]
    Auto = 0,
    #[pyo3(name = "CPU")]
    Cpu = 1,
    #[pyo3(name = "CORE_ML")]
    CoreMl = 2,
    #[pyo3(name = "CUDA")]
    Cuda = 3,
    #[pyo3(name = "TENSOR_RT")]
    TensorRt = 4,
}
#[pymethods]
impl ExecutionProviderType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| {
                pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ExecutionProviderType: {e}"))
            })
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone)]
#[pyclass(frozen)]
pub struct OutputFormat {
    pub(crate) inner: kreuzberg::OutputFormat,
}

#[pymethods]
impl OutputFormat {
    #[new]
    fn new(py: Python<'_>, value: &Bound<'_, pyo3::types::PyAny>) -> PyResult<Self> {
        // Accept either a Python dict (full tagged-union shape) or a string
        // (the unit variant name). Strings are wrapped in `"..."` so serde_json
        // can deserialize into a unit-variant of the tagged enum.
        let json_str: String = if let Ok(s) = value.extract::<String>() {
            serde_json::to_string(&s)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid OutputFormat: {e}")))?
        } else {
            let json_mod = py.import("json")?;
            json_mod.call_method1("dumps", (value,))?.extract()?
        };
        let inner: kreuzberg::OutputFormat = serde_json::from_str(&json_str)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid OutputFormat: {e}")))?;
        Ok(Self { inner })
    }

    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(&self.inner)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize OutputFormat: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }

    #[getter]
    fn plain(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "tag";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "plain" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn markdown(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "tag";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "markdown" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn djot(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "tag";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "djot" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn html(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "tag";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "html" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn json(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "tag";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "json" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn structured(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "tag";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "structured" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn custom(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "tag";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "custom" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }
}

impl From<OutputFormat> for kreuzberg::OutputFormat {
    fn from(val: OutputFormat) -> Self {
        val.inner
    }
}

impl From<kreuzberg::OutputFormat> for OutputFormat {
    fn from(val: kreuzberg::OutputFormat) -> Self {
        Self { inner: val }
    }
}

impl serde::Serialize for OutputFormat {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.inner.serialize(serializer)
    }
}

impl Default for OutputFormat {
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl<'de> serde::Deserialize<'de> for OutputFormat {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let inner = kreuzberg::OutputFormat::deserialize(deserializer)?;
        Ok(Self { inner })
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum HtmlTheme {
    #[pyo3(name = "DEFAULT")]
    Default = 0,
    #[pyo3(name = "GIT_HUB")]
    GitHub = 1,
    #[pyo3(name = "DARK")]
    Dark = 2,
    #[pyo3(name = "LIGHT")]
    Light = 3,
    #[pyo3(name = "UNSTYLED")]
    #[default]
    Unstyled = 4,
}
#[pymethods]
impl HtmlTheme {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize HtmlTheme: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum TableModel {
    #[pyo3(name = "TATR")]
    #[default]
    Tatr = 0,
    #[pyo3(name = "SLANET_WIRED")]
    SlanetWired = 1,
    #[pyo3(name = "SLANET_WIRELESS")]
    SlanetWireless = 2,
    #[pyo3(name = "SLANET_PLUS")]
    SlanetPlus = 3,
    #[pyo3(name = "SLANET_AUTO")]
    SlanetAuto = 4,
    #[pyo3(name = "DISABLED")]
    Disabled = 5,
}
#[pymethods]
impl TableModel {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize TableModel: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ChunkerType {
    #[pyo3(name = "TEXT")]
    #[default]
    Text = 0,
    #[pyo3(name = "MARKDOWN")]
    Markdown = 1,
    #[pyo3(name = "YAML")]
    Yaml = 2,
    #[pyo3(name = "SEMANTIC")]
    Semantic = 3,
}
#[pymethods]
impl ChunkerType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ChunkerType: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone)]
#[pyclass(frozen)]
pub struct ChunkSizing {
    pub(crate) inner: kreuzberg::ChunkSizing,
}

#[pymethods]
impl ChunkSizing {
    #[new]
    fn new(py: Python<'_>, value: &Bound<'_, pyo3::types::PyAny>) -> PyResult<Self> {
        // Accept either a Python dict (full tagged-union shape) or a string
        // (the unit variant name). Strings are wrapped in `"..."` so serde_json
        // can deserialize into a unit-variant of the tagged enum.
        let json_str: String = if let Ok(s) = value.extract::<String>() {
            serde_json::to_string(&s)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid ChunkSizing: {e}")))?
        } else {
            let json_mod = py.import("json")?;
            json_mod.call_method1("dumps", (value,))?.extract()?
        };
        let inner: kreuzberg::ChunkSizing = serde_json::from_str(&json_str)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid ChunkSizing: {e}")))?;
        Ok(Self { inner })
    }

    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(&self.inner)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ChunkSizing: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }

    #[getter]
    fn characters(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "characters" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn tokenizer(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "tokenizer" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn r#type(&self) -> pyo3::PyResult<String> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        json.get("type")
            .and_then(|v| v.as_str())
            .map(String::from)
            .ok_or_else(|| pyo3::exceptions::PyRuntimeError::new_err("type not found in serialized enum"))
    }
}

impl From<ChunkSizing> for kreuzberg::ChunkSizing {
    fn from(val: ChunkSizing) -> Self {
        val.inner
    }
}

impl From<kreuzberg::ChunkSizing> for ChunkSizing {
    fn from(val: kreuzberg::ChunkSizing) -> Self {
        Self { inner: val }
    }
}

impl serde::Serialize for ChunkSizing {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.inner.serialize(serializer)
    }
}

impl Default for ChunkSizing {
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl<'de> serde::Deserialize<'de> for ChunkSizing {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let inner = kreuzberg::ChunkSizing::deserialize(deserializer)?;
        Ok(Self { inner })
    }
}

#[derive(Clone)]
#[pyclass(frozen)]
pub struct EmbeddingModelType {
    pub(crate) inner: kreuzberg::EmbeddingModelType,
}

#[pymethods]
impl EmbeddingModelType {
    #[new]
    fn new(py: Python<'_>, value: &Bound<'_, pyo3::types::PyAny>) -> PyResult<Self> {
        // Accept either a Python dict (full tagged-union shape) or a string
        // (the unit variant name). Strings are wrapped in `"..."` so serde_json
        // can deserialize into a unit-variant of the tagged enum.
        let json_str: String = if let Ok(s) = value.extract::<String>() {
            serde_json::to_string(&s)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid EmbeddingModelType: {e}")))?
        } else {
            let json_mod = py.import("json")?;
            json_mod.call_method1("dumps", (value,))?.extract()?
        };
        let inner: kreuzberg::EmbeddingModelType = serde_json::from_str(&json_str)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid EmbeddingModelType: {e}")))?;
        Ok(Self { inner })
    }

    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(&self.inner)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| {
                pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize EmbeddingModelType: {e}"))
            })
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }

    #[getter]
    fn preset(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "preset" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn custom(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "custom" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn llm(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "llm" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn plugin(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "plugin" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn r#type(&self) -> pyo3::PyResult<String> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        json.get("type")
            .and_then(|v| v.as_str())
            .map(String::from)
            .ok_or_else(|| pyo3::exceptions::PyRuntimeError::new_err("type not found in serialized enum"))
    }
}

impl From<EmbeddingModelType> for kreuzberg::EmbeddingModelType {
    fn from(val: EmbeddingModelType) -> Self {
        val.inner
    }
}

impl From<kreuzberg::EmbeddingModelType> for EmbeddingModelType {
    fn from(val: kreuzberg::EmbeddingModelType) -> Self {
        Self { inner: val }
    }
}

impl serde::Serialize for EmbeddingModelType {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.inner.serialize(serializer)
    }
}

impl Default for EmbeddingModelType {
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl<'de> serde::Deserialize<'de> for EmbeddingModelType {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let inner = kreuzberg::EmbeddingModelType::deserialize(deserializer)?;
        Ok(Self { inner })
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum CodeContentMode {
    #[pyo3(name = "CHUNKS")]
    #[default]
    Chunks = 0,
    #[pyo3(name = "RAW")]
    Raw = 1,
    #[pyo3(name = "STRUCTURE")]
    Structure = 2,
}
#[pymethods]
impl CodeContentMode {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize CodeContentMode: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ListType {
    #[pyo3(name = "BULLET")]
    #[default]
    Bullet = 0,
    #[pyo3(name = "NUMBERED")]
    Numbered = 1,
    #[pyo3(name = "LETTERED")]
    Lettered = 2,
    #[pyo3(name = "INDENTED")]
    Indented = 3,
}
#[pymethods]
impl ListType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ListType: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(eq, eq_int, from_py_object)]
pub enum OcrBackendType {
    #[pyo3(name = "TESSERACT")]
    #[default]
    Tesseract = 0,
    #[pyo3(name = "EASY_OCR")]
    EasyOCR = 1,
    #[pyo3(name = "PADDLE_OCR")]
    PaddleOCR = 2,
    #[pyo3(name = "CUSTOM")]
    Custom = 3,
}
#[pymethods]
impl OcrBackendType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize OcrBackendType: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ProcessingStage {
    #[pyo3(name = "EARLY")]
    #[default]
    Early = 0,
    #[pyo3(name = "MIDDLE")]
    Middle = 1,
    #[pyo3(name = "LATE")]
    Late = 2,
}
#[pymethods]
impl ProcessingStage {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ProcessingStage: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ReductionLevel {
    #[pyo3(name = "OFF")]
    #[default]
    Off = 0,
    #[pyo3(name = "LIGHT")]
    Light = 1,
    #[pyo3(name = "MODERATE")]
    Moderate = 2,
    #[pyo3(name = "AGGRESSIVE")]
    Aggressive = 3,
    #[pyo3(name = "MAXIMUM")]
    Maximum = 4,
}
#[pymethods]
impl ReductionLevel {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ReductionLevel: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum PdfAnnotationType {
    #[pyo3(name = "TEXT")]
    #[default]
    Text = 0,
    #[pyo3(name = "HIGHLIGHT")]
    Highlight = 1,
    #[pyo3(name = "LINK")]
    Link = 2,
    #[pyo3(name = "STAMP")]
    Stamp = 3,
    #[pyo3(name = "UNDERLINE")]
    Underline = 4,
    #[pyo3(name = "STRIKE_OUT")]
    StrikeOut = 5,
    #[pyo3(name = "OTHER")]
    Other = 6,
}
#[pymethods]
impl PdfAnnotationType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| {
                pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize PdfAnnotationType: {e}"))
            })
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum BlockType {
    #[pyo3(name = "PARAGRAPH")]
    #[default]
    Paragraph = 0,
    #[pyo3(name = "HEADING")]
    Heading = 1,
    #[pyo3(name = "BLOCKQUOTE")]
    Blockquote = 2,
    #[pyo3(name = "CODE_BLOCK")]
    CodeBlock = 3,
    #[pyo3(name = "LIST_ITEM")]
    ListItem = 4,
    #[pyo3(name = "ORDERED_LIST")]
    OrderedList = 5,
    #[pyo3(name = "BULLET_LIST")]
    BulletList = 6,
    #[pyo3(name = "TASK_LIST")]
    TaskList = 7,
    #[pyo3(name = "DEFINITION_LIST")]
    DefinitionList = 8,
    #[pyo3(name = "DEFINITION_TERM")]
    DefinitionTerm = 9,
    #[pyo3(name = "DEFINITION_DESCRIPTION")]
    DefinitionDescription = 10,
    #[pyo3(name = "DIV")]
    Div = 11,
    #[pyo3(name = "SECTION")]
    Section = 12,
    #[pyo3(name = "THEMATIC_BREAK")]
    ThematicBreak = 13,
    #[pyo3(name = "RAW_BLOCK")]
    RawBlock = 14,
    #[pyo3(name = "MATH_DISPLAY")]
    MathDisplay = 15,
}
#[pymethods]
impl BlockType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize BlockType: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum InlineType {
    #[pyo3(name = "TEXT")]
    #[default]
    Text = 0,
    #[pyo3(name = "STRONG")]
    Strong = 1,
    #[pyo3(name = "EMPHASIS")]
    Emphasis = 2,
    #[pyo3(name = "HIGHLIGHT")]
    Highlight = 3,
    #[pyo3(name = "SUBSCRIPT")]
    Subscript = 4,
    #[pyo3(name = "SUPERSCRIPT")]
    Superscript = 5,
    #[pyo3(name = "INSERT")]
    Insert = 6,
    #[pyo3(name = "DELETE")]
    Delete = 7,
    #[pyo3(name = "CODE")]
    Code = 8,
    #[pyo3(name = "LINK")]
    Link = 9,
    #[pyo3(name = "IMAGE")]
    Image = 10,
    #[pyo3(name = "SPAN")]
    Span = 11,
    #[pyo3(name = "MATH")]
    Math = 12,
    #[pyo3(name = "RAW_INLINE")]
    RawInline = 13,
    #[pyo3(name = "FOOTNOTE_REF")]
    FootnoteRef = 14,
    #[pyo3(name = "SYMBOL")]
    Symbol = 15,
}
#[pymethods]
impl InlineType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize InlineType: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum RelationshipKind {
    #[pyo3(name = "FOOTNOTE_REFERENCE")]
    #[default]
    FootnoteReference = 0,
    #[pyo3(name = "CITATION_REFERENCE")]
    CitationReference = 1,
    #[pyo3(name = "INTERNAL_LINK")]
    InternalLink = 2,
    #[pyo3(name = "CAPTION")]
    Caption = 3,
    #[pyo3(name = "LABEL")]
    Label = 4,
    #[pyo3(name = "TOC_ENTRY")]
    TocEntry = 5,
    #[pyo3(name = "CROSS_REFERENCE")]
    CrossReference = 6,
}
#[pymethods]
impl RelationshipKind {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| {
                pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize RelationshipKind: {e}"))
            })
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ContentLayer {
    #[pyo3(name = "BODY")]
    #[default]
    Body = 0,
    #[pyo3(name = "HEADER")]
    Header = 1,
    #[pyo3(name = "FOOTER")]
    Footer = 2,
    #[pyo3(name = "FOOTNOTE")]
    Footnote = 3,
}
#[pymethods]
impl ContentLayer {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ContentLayer: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone)]
#[pyclass(frozen)]
pub struct NodeContent {
    pub(crate) inner: kreuzberg::NodeContent,
}

#[pymethods]
impl NodeContent {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(&self.inner)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize NodeContent: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }

    #[getter]
    fn title(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "title" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn heading(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "heading" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn paragraph(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "paragraph" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn list(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "list" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn list_item(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "list_item" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn table(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "table" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn image(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "image" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn code(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "code" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn quote(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "quote" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn formula(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "formula" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn footnote(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "footnote" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn group(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "group" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn page_break(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "page_break" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn slide(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "slide" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn definition_list(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "definition_list" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn definition_item(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "definition_item" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn citation(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "citation" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn admonition(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "admonition" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn raw_block(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "raw_block" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn metadata_block(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "node_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "metadata_block" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn node_type(&self) -> pyo3::PyResult<String> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        json.get("node_type")
            .and_then(|v| v.as_str())
            .map(String::from)
            .ok_or_else(|| pyo3::exceptions::PyRuntimeError::new_err("node_type not found in serialized enum"))
    }
}

impl From<NodeContent> for kreuzberg::NodeContent {
    fn from(val: NodeContent) -> Self {
        val.inner
    }
}

impl From<kreuzberg::NodeContent> for NodeContent {
    fn from(val: kreuzberg::NodeContent) -> Self {
        Self { inner: val }
    }
}

impl serde::Serialize for NodeContent {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.inner.serialize(serializer)
    }
}

impl Default for NodeContent {
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl<'de> serde::Deserialize<'de> for NodeContent {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let inner = kreuzberg::NodeContent::deserialize(deserializer)?;
        Ok(Self { inner })
    }
}

#[derive(Clone)]
#[pyclass(frozen)]
pub struct AnnotationKind {
    pub(crate) inner: kreuzberg::AnnotationKind,
}

#[pymethods]
impl AnnotationKind {
    #[new]
    fn new(py: Python<'_>, value: &Bound<'_, pyo3::types::PyAny>) -> PyResult<Self> {
        // Accept either a Python dict (full tagged-union shape) or a string
        // (the unit variant name). Strings are wrapped in `"..."` so serde_json
        // can deserialize into a unit-variant of the tagged enum.
        let json_str: String = if let Ok(s) = value.extract::<String>() {
            serde_json::to_string(&s)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid AnnotationKind: {e}")))?
        } else {
            let json_mod = py.import("json")?;
            json_mod.call_method1("dumps", (value,))?.extract()?
        };
        let inner: kreuzberg::AnnotationKind = serde_json::from_str(&json_str)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid AnnotationKind: {e}")))?;
        Ok(Self { inner })
    }

    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(&self.inner)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize AnnotationKind: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }

    #[getter]
    fn bold(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "bold" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn italic(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "italic" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn underline(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "underline" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn strikethrough(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "strikethrough" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn code(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "code" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn subscript(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "subscript" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn superscript(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "superscript" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn link(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "link" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn highlight(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "highlight" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn color(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "color" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn font_size(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "font_size" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn custom(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "annotation_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "custom" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn annotation_type(&self) -> pyo3::PyResult<String> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        json.get("annotation_type")
            .and_then(|v| v.as_str())
            .map(String::from)
            .ok_or_else(|| pyo3::exceptions::PyRuntimeError::new_err("annotation_type not found in serialized enum"))
    }
}

impl From<AnnotationKind> for kreuzberg::AnnotationKind {
    fn from(val: AnnotationKind) -> Self {
        val.inner
    }
}

impl From<kreuzberg::AnnotationKind> for AnnotationKind {
    fn from(val: kreuzberg::AnnotationKind) -> Self {
        Self { inner: val }
    }
}

impl serde::Serialize for AnnotationKind {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.inner.serialize(serializer)
    }
}

impl Default for AnnotationKind {
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl<'de> serde::Deserialize<'de> for AnnotationKind {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let inner = kreuzberg::AnnotationKind::deserialize(deserializer)?;
        Ok(Self { inner })
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ExtractionMethod {
    #[pyo3(name = "NATIVE")]
    #[default]
    Native = 0,
    #[pyo3(name = "OCR")]
    Ocr = 1,
    #[pyo3(name = "MIXED")]
    Mixed = 2,
}
#[pymethods]
impl ExtractionMethod {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| {
                pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ExtractionMethod: {e}"))
            })
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ChunkType {
    #[pyo3(name = "HEADING")]
    Heading = 0,
    #[pyo3(name = "PARTY_LIST")]
    PartyList = 1,
    #[pyo3(name = "DEFINITIONS")]
    Definitions = 2,
    #[pyo3(name = "OPERATIVE_CLAUSE")]
    OperativeClause = 3,
    #[pyo3(name = "SIGNATURE_BLOCK")]
    SignatureBlock = 4,
    #[pyo3(name = "SCHEDULE")]
    Schedule = 5,
    #[pyo3(name = "TABLE_LIKE")]
    TableLike = 6,
    #[pyo3(name = "FORMULA")]
    Formula = 7,
    #[pyo3(name = "CODE_BLOCK")]
    CodeBlock = 8,
    #[pyo3(name = "IMAGE")]
    Image = 9,
    #[pyo3(name = "ORG_CHART")]
    OrgChart = 10,
    #[pyo3(name = "DIAGRAM")]
    Diagram = 11,
    #[pyo3(name = "UNKNOWN")]
    #[default]
    Unknown = 12,
}
#[pymethods]
impl ChunkType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ChunkType: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ImageKind {
    #[pyo3(name = "PHOTOGRAPH")]
    #[default]
    Photograph = 0,
    #[pyo3(name = "DIAGRAM")]
    Diagram = 1,
    #[pyo3(name = "CHART")]
    Chart = 2,
    #[pyo3(name = "DRAWING")]
    Drawing = 3,
    #[pyo3(name = "TEXT_BLOCK")]
    TextBlock = 4,
    #[pyo3(name = "DECORATION")]
    Decoration = 5,
    #[pyo3(name = "LOGO")]
    Logo = 6,
    #[pyo3(name = "ICON")]
    Icon = 7,
    #[pyo3(name = "TILE_FRAGMENT")]
    TileFragment = 8,
    #[pyo3(name = "MASK")]
    Mask = 9,
    #[pyo3(name = "PAGE_RASTER")]
    PageRaster = 10,
    #[pyo3(name = "UNKNOWN")]
    Unknown = 11,
}
#[pymethods]
impl ImageKind {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ImageKind: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ResultFormat {
    #[pyo3(name = "UNIFIED")]
    #[default]
    Unified = 0,
    #[pyo3(name = "ELEMENT_BASED")]
    ElementBased = 1,
}
#[pymethods]
impl ResultFormat {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ResultFormat: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ElementType {
    #[pyo3(name = "TITLE")]
    #[default]
    Title = 0,
    #[pyo3(name = "NARRATIVE_TEXT")]
    NarrativeText = 1,
    #[pyo3(name = "HEADING")]
    Heading = 2,
    #[pyo3(name = "LIST_ITEM")]
    ListItem = 3,
    #[pyo3(name = "TABLE")]
    Table = 4,
    #[pyo3(name = "IMAGE")]
    Image = 5,
    #[pyo3(name = "PAGE_BREAK")]
    PageBreak = 6,
    #[pyo3(name = "CODE_BLOCK")]
    CodeBlock = 7,
    #[pyo3(name = "BLOCK_QUOTE")]
    BlockQuote = 8,
    #[pyo3(name = "FOOTER")]
    Footer = 9,
    #[pyo3(name = "HEADER")]
    Header = 10,
}
#[pymethods]
impl ElementType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ElementType: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone)]
#[pyclass(frozen)]
pub struct FormatMetadata {
    pub(crate) inner: kreuzberg::FormatMetadata,
}

#[pymethods]
impl FormatMetadata {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(&self.inner)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize FormatMetadata: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }

    #[getter]
    fn pdf(&self) -> Option<PdfMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Pdf(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn docx(&self) -> Option<DocxMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Docx(data) => Some((**data).clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn excel(&self) -> Option<ExcelMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Excel(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn email(&self) -> Option<EmailMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Email(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn pptx(&self) -> Option<PptxMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Pptx(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn archive(&self) -> Option<ArchiveMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Archive(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn image(&self) -> Option<ImageMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Image(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn xml(&self) -> Option<XmlMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Xml(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn text(&self) -> Option<TextMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Text(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn html(&self) -> Option<HtmlMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Html(data) => Some((**data).clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn ocr(&self) -> Option<OcrMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Ocr(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn csv(&self) -> Option<CsvMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Csv(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn bibtex(&self) -> Option<BibtexMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Bibtex(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn citation(&self) -> Option<CitationMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Citation(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn fiction_book(&self) -> Option<FictionBookMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::FictionBook(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn dbf(&self) -> Option<DbfMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Dbf(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn jats(&self) -> Option<JatsMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Jats(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn epub(&self) -> Option<EpubMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Epub(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn pst(&self) -> Option<PstMetadata> {
        match &self.inner {
            kreuzberg::FormatMetadata::Pst(data) => Some(data.clone().into()),
            _ => None,
        }
    }

    #[getter]
    fn code(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "format_type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "code" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn format_type(&self) -> pyo3::PyResult<String> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        json.get("format_type")
            .and_then(|v| v.as_str())
            .map(String::from)
            .ok_or_else(|| pyo3::exceptions::PyRuntimeError::new_err("format_type not found in serialized enum"))
    }
}

impl From<FormatMetadata> for kreuzberg::FormatMetadata {
    fn from(val: FormatMetadata) -> Self {
        val.inner
    }
}

impl From<kreuzberg::FormatMetadata> for FormatMetadata {
    fn from(val: kreuzberg::FormatMetadata) -> Self {
        Self { inner: val }
    }
}

impl serde::Serialize for FormatMetadata {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.inner.serialize(serializer)
    }
}

impl Default for FormatMetadata {
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl<'de> serde::Deserialize<'de> for FormatMetadata {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let inner = kreuzberg::FormatMetadata::deserialize(deserializer)?;
        Ok(Self { inner })
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum TextDirection {
    #[pyo3(name = "LEFT_TO_RIGHT")]
    #[default]
    #[serde(rename = "ltr")]
    LeftToRight = 0,
    #[pyo3(name = "RIGHT_TO_LEFT")]
    #[serde(rename = "rtl")]
    RightToLeft = 1,
    #[pyo3(name = "AUTO")]
    #[serde(rename = "auto")]
    Auto = 2,
}
#[pymethods]
impl TextDirection {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize TextDirection: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum LinkType {
    #[pyo3(name = "ANCHOR")]
    #[default]
    Anchor = 0,
    #[pyo3(name = "INTERNAL")]
    Internal = 1,
    #[pyo3(name = "EXTERNAL")]
    External = 2,
    #[pyo3(name = "EMAIL")]
    Email = 3,
    #[pyo3(name = "PHONE")]
    Phone = 4,
    #[pyo3(name = "OTHER")]
    Other = 5,
}
#[pymethods]
impl LinkType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize LinkType: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum ImageType {
    #[pyo3(name = "DATA_URI")]
    #[default]
    #[serde(rename = "data-uri")]
    DataUri = 0,
    #[pyo3(name = "INLINE_SVG")]
    #[serde(rename = "inline-svg")]
    InlineSvg = 1,
    #[pyo3(name = "EXTERNAL")]
    External = 2,
    #[pyo3(name = "RELATIVE")]
    Relative = 3,
}
#[pymethods]
impl ImageType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize ImageType: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum StructuredDataType {
    #[pyo3(name = "JSON_LD")]
    #[default]
    #[serde(rename = "json-ld")]
    JsonLd = 0,
    #[pyo3(name = "MICRODATA")]
    Microdata = 1,
    #[pyo3(name = "RDFA")]
    #[serde(rename = "rdfa")]
    RDFa = 2,
}
#[pymethods]
impl StructuredDataType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| {
                pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize StructuredDataType: {e}"))
            })
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone)]
#[pyclass(frozen)]
pub struct OcrBoundingGeometry {
    pub(crate) inner: kreuzberg::OcrBoundingGeometry,
}

#[pymethods]
impl OcrBoundingGeometry {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(&self.inner)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| {
                pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize OcrBoundingGeometry: {e}"))
            })
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }

    #[getter]
    fn rectangle(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "rectangle" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn quadrilateral(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "quadrilateral" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn r#type(&self) -> pyo3::PyResult<String> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        json.get("type")
            .and_then(|v| v.as_str())
            .map(String::from)
            .ok_or_else(|| pyo3::exceptions::PyRuntimeError::new_err("type not found in serialized enum"))
    }
}

impl From<OcrBoundingGeometry> for kreuzberg::OcrBoundingGeometry {
    fn from(val: OcrBoundingGeometry) -> Self {
        val.inner
    }
}

impl From<kreuzberg::OcrBoundingGeometry> for OcrBoundingGeometry {
    fn from(val: kreuzberg::OcrBoundingGeometry) -> Self {
        Self { inner: val }
    }
}

impl serde::Serialize for OcrBoundingGeometry {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.inner.serialize(serializer)
    }
}

impl Default for OcrBoundingGeometry {
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl<'de> serde::Deserialize<'de> for OcrBoundingGeometry {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let inner = kreuzberg::OcrBoundingGeometry::deserialize(deserializer)?;
        Ok(Self { inner })
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum OcrElementLevel {
    #[pyo3(name = "WORD")]
    Word = 0,
    #[pyo3(name = "LINE")]
    #[default]
    Line = 1,
    #[pyo3(name = "BLOCK")]
    Block = 2,
    #[pyo3(name = "PAGE")]
    Page = 3,
}
#[pymethods]
impl OcrElementLevel {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize OcrElementLevel: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum PageUnitType {
    #[pyo3(name = "PAGE")]
    #[default]
    Page = 0,
    #[pyo3(name = "SLIDE")]
    Slide = 1,
    #[pyo3(name = "SHEET")]
    Sheet = 2,
}
#[pymethods]
impl PageUnitType {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize PageUnitType: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone)]
#[pyclass(frozen)]
pub struct DiffLine {
    pub(crate) inner: kreuzberg::DiffLine,
}

#[pymethods]
impl DiffLine {
    #[new]
    fn new(py: Python<'_>, value: &Bound<'_, pyo3::types::PyAny>) -> PyResult<Self> {
        // Accept either a Python dict (full tagged-union shape) or a string
        // (the unit variant name). Strings are wrapped in `"..."` so serde_json
        // can deserialize into a unit-variant of the tagged enum.
        let json_str: String = if let Ok(s) = value.extract::<String>() {
            serde_json::to_string(&s)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid DiffLine: {e}")))?
        } else {
            let json_mod = py.import("json")?;
            json_mod.call_method1("dumps", (value,))?.extract()?
        };
        let inner: kreuzberg::DiffLine = serde_json::from_str(&json_str)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid DiffLine: {e}")))?;
        Ok(Self { inner })
    }

    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(&self.inner)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize DiffLine: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }

    #[getter]
    fn context(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "kind";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "context" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn added(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "kind";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "added" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn removed(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "kind";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "removed" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn kind(&self) -> pyo3::PyResult<String> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        json.get("kind")
            .and_then(|v| v.as_str())
            .map(String::from)
            .ok_or_else(|| pyo3::exceptions::PyRuntimeError::new_err("kind not found in serialized enum"))
    }
}

impl From<DiffLine> for kreuzberg::DiffLine {
    fn from(val: DiffLine) -> Self {
        val.inner
    }
}

impl From<kreuzberg::DiffLine> for DiffLine {
    fn from(val: kreuzberg::DiffLine) -> Self {
        Self { inner: val }
    }
}

impl serde::Serialize for DiffLine {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.inner.serialize(serializer)
    }
}

impl Default for DiffLine {
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl<'de> serde::Deserialize<'de> for DiffLine {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let inner = kreuzberg::DiffLine::deserialize(deserializer)?;
        Ok(Self { inner })
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum RevisionKind {
    #[pyo3(name = "INSERTION")]
    #[default]
    Insertion = 0,
    #[pyo3(name = "DELETION")]
    Deletion = 1,
    #[pyo3(name = "FORMAT_CHANGE")]
    FormatChange = 2,
    #[pyo3(name = "COMMENT")]
    Comment = 3,
}
#[pymethods]
impl RevisionKind {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize RevisionKind: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone)]
#[pyclass(frozen)]
pub struct RevisionAnchor {
    pub(crate) inner: kreuzberg::RevisionAnchor,
}

#[pymethods]
impl RevisionAnchor {
    #[new]
    fn new(py: Python<'_>, value: &Bound<'_, pyo3::types::PyAny>) -> PyResult<Self> {
        // Accept either a Python dict (full tagged-union shape) or a string
        // (the unit variant name). Strings are wrapped in `"..."` so serde_json
        // can deserialize into a unit-variant of the tagged enum.
        let json_str: String = if let Ok(s) = value.extract::<String>() {
            serde_json::to_string(&s)
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid RevisionAnchor: {e}")))?
        } else {
            let json_mod = py.import("json")?;
            json_mod.call_method1("dumps", (value,))?.extract()?
        };
        let inner: kreuzberg::RevisionAnchor = serde_json::from_str(&json_str)
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid RevisionAnchor: {e}")))?;
        Ok(Self { inner })
    }

    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(&self.inner)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize RevisionAnchor: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }

    #[getter]
    fn paragraph(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "paragraph" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn table_cell(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "table_cell" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn page(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "page" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn slide(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "slide" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn sheet(&self, py: Python<'_>) -> PyResult<Option<pyo3::Py<pyo3::types::PyDict>>> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        let tag_field = "type";
        let tag_value = json.get(tag_field).and_then(|v| v.as_str()).unwrap_or("");
        if tag_value != "sheet" {
            return Ok(None);
        }
        let json_str = json.to_string();
        let json_mod = py.import("json")?;
        let py_dict = json_mod
            .call_method1("loads", (&json_str,))?
            .downcast_into::<pyo3::types::PyDict>()?;
        Ok(Some(py_dict.unbind()))
    }

    #[getter]
    fn r#type(&self) -> pyo3::PyResult<String> {
        let json =
            serde_json::to_value(&self.inner).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
        json.get("type")
            .and_then(|v| v.as_str())
            .map(String::from)
            .ok_or_else(|| pyo3::exceptions::PyRuntimeError::new_err("type not found in serialized enum"))
    }
}

impl From<RevisionAnchor> for kreuzberg::RevisionAnchor {
    fn from(val: RevisionAnchor) -> Self {
        val.inner
    }
}

impl From<kreuzberg::RevisionAnchor> for RevisionAnchor {
    fn from(val: kreuzberg::RevisionAnchor) -> Self {
        Self { inner: val }
    }
}

impl serde::Serialize for RevisionAnchor {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.inner.serialize(serializer)
    }
}

impl Default for RevisionAnchor {
    fn default() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl<'de> serde::Deserialize<'de> for RevisionAnchor {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let inner = kreuzberg::RevisionAnchor::deserialize(deserializer)?;
        Ok(Self { inner })
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum UriKind {
    #[pyo3(name = "HYPERLINK")]
    #[default]
    Hyperlink = 0,
    #[pyo3(name = "IMAGE")]
    Image = 1,
    #[pyo3(name = "ANCHOR")]
    Anchor = 2,
    #[pyo3(name = "CITATION")]
    Citation = 3,
    #[pyo3(name = "REFERENCE")]
    Reference = 4,
    #[pyo3(name = "EMAIL")]
    Email = 5,
}
#[pymethods]
impl UriKind {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize UriKind: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum KeywordAlgorithm {
    #[pyo3(name = "YAKE")]
    #[default]
    Yake = 0,
    #[pyo3(name = "RAKE")]
    Rake = 1,
}
#[pymethods]
impl KeywordAlgorithm {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| {
                pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize KeywordAlgorithm: {e}"))
            })
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(eq, eq_int, from_py_object)]
pub enum PSMMode {
    #[pyo3(name = "OSD_ONLY")]
    #[default]
    OsdOnly = 0,
    #[pyo3(name = "AUTO_OSD")]
    AutoOsd = 1,
    #[pyo3(name = "AUTO_ONLY")]
    AutoOnly = 2,
    #[pyo3(name = "AUTO")]
    Auto = 3,
    #[pyo3(name = "SINGLE_COLUMN")]
    SingleColumn = 4,
    #[pyo3(name = "SINGLE_BLOCK_VERTICAL")]
    SingleBlockVertical = 5,
    #[pyo3(name = "SINGLE_BLOCK")]
    SingleBlock = 6,
    #[pyo3(name = "SINGLE_LINE")]
    SingleLine = 7,
    #[pyo3(name = "SINGLE_WORD")]
    SingleWord = 8,
    #[pyo3(name = "CIRCLE_WORD")]
    CircleWord = 9,
    #[pyo3(name = "SINGLE_CHAR")]
    SingleChar = 10,
}
#[pymethods]
impl PSMMode {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize PSMMode: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[pyclass(eq, eq_int, from_py_object)]
pub enum PaddleLanguage {
    #[pyo3(name = "ENGLISH")]
    #[default]
    English = 0,
    #[pyo3(name = "CHINESE")]
    Chinese = 1,
    #[pyo3(name = "JAPANESE")]
    Japanese = 2,
    #[pyo3(name = "KOREAN")]
    Korean = 3,
    #[pyo3(name = "GERMAN")]
    German = 4,
    #[pyo3(name = "FRENCH")]
    French = 5,
    #[pyo3(name = "LATIN")]
    Latin = 6,
    #[pyo3(name = "CYRILLIC")]
    Cyrillic = 7,
    #[pyo3(name = "TRADITIONAL_CHINESE")]
    TraditionalChinese = 8,
    #[pyo3(name = "THAI")]
    Thai = 9,
    #[pyo3(name = "GREEK")]
    Greek = 10,
    #[pyo3(name = "EAST_SLAVIC")]
    EastSlavic = 11,
    #[pyo3(name = "ARABIC")]
    Arabic = 12,
    #[pyo3(name = "DEVANAGARI")]
    Devanagari = 13,
    #[pyo3(name = "TAMIL")]
    Tamil = 14,
    #[pyo3(name = "TELUGU")]
    Telugu = 15,
}
#[pymethods]
impl PaddleLanguage {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize PaddleLanguage: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[derive(Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
#[pyclass(eq, eq_int, from_py_object)]
pub enum LayoutClass {
    #[pyo3(name = "CAPTION")]
    #[default]
    Caption = 0,
    #[pyo3(name = "FOOTNOTE")]
    Footnote = 1,
    #[pyo3(name = "FORMULA")]
    Formula = 2,
    #[pyo3(name = "LIST_ITEM")]
    ListItem = 3,
    #[pyo3(name = "PAGE_FOOTER")]
    PageFooter = 4,
    #[pyo3(name = "PAGE_HEADER")]
    PageHeader = 5,
    #[pyo3(name = "PICTURE")]
    Picture = 6,
    #[pyo3(name = "SECTION_HEADER")]
    SectionHeader = 7,
    #[pyo3(name = "TABLE")]
    Table = 8,
    #[pyo3(name = "TEXT")]
    Text = 9,
    #[pyo3(name = "TITLE")]
    Title = 10,
    #[pyo3(name = "DOCUMENT_INDEX")]
    DocumentIndex = 11,
    #[pyo3(name = "CODE")]
    Code = 12,
    #[pyo3(name = "CHECKBOX_SELECTED")]
    CheckboxSelected = 13,
    #[pyo3(name = "CHECKBOX_UNSELECTED")]
    CheckboxUnselected = 14,
    #[pyo3(name = "FORM")]
    Form = 15,
    #[pyo3(name = "KEY_VALUE_REGION")]
    KeyValueRegion = 16,
}
#[pymethods]
impl LayoutClass {
    fn __str__(&self) -> PyResult<String> {
        serde_json::to_value(self)
            .map(|value| match value {
                serde_json::Value::String(value) => value,
                other => other.to_string(),
            })
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to serialize LayoutClass: {e}")))
    }

    fn __repr__(&self) -> PyResult<String> {
        self.__str__()
    }
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (content, mime_type, config))]
pub fn extract_bytes<'py>(
    py: Python<'py>,
    content: Vec<u8>,
    mime_type: String,
    config: ExtractionConfig,
) -> PyResult<Bound<'py, PyAny>> {
    let config_core: kreuzberg::ExtractionConfig = config.into();

    pyo3_async_runtimes::tokio::future_into_py(py, async move {
        let result = kreuzberg::extract_bytes(&content, &mime_type, &config_core)
            .await
            .map_err(|e| PyErr::new::<PyRuntimeError, _>(e.to_string()))?;
        let wrapped_result: ExtractionResult = ExtractionResult::from(result);

        Ok(wrapped_result)
    })
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (path, mime_type=None, config=None))]
pub fn extract_file<'py>(
    py: Python<'py>,
    path: String,
    mime_type: Option<String>,
    config: Option<ExtractionConfig>,
) -> PyResult<Bound<'py, PyAny>> {
    let config_core: kreuzberg::ExtractionConfig = config.unwrap_or_default().into();

    pyo3_async_runtimes::tokio::future_into_py(py, async move {
        let result = kreuzberg::extract_file(std::path::PathBuf::from(path), mime_type.as_deref(), &config_core)
            .await
            .map_err(|e| PyErr::new::<PyRuntimeError, _>(e.to_string()))?;
        let wrapped_result: ExtractionResult = ExtractionResult::from(result);

        Ok(wrapped_result)
    })
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (path, mime_type=None, config=None))]
pub fn extract_file_sync(
    path: String,
    mime_type: Option<String>,
    config: Option<ExtractionConfig>,
) -> PyResult<ExtractionResult> {
    let config_core: kreuzberg::ExtractionConfig = config.unwrap_or_default().into();

    kreuzberg::extract_file_sync(std::path::PathBuf::from(path), mime_type.as_deref(), &config_core)
        .map(Into::into)
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (content, mime_type, config))]
pub fn extract_bytes_sync(content: Vec<u8>, mime_type: String, config: ExtractionConfig) -> PyResult<ExtractionResult> {
    let config_core: kreuzberg::ExtractionConfig = config.into();

    kreuzberg::extract_bytes_sync(&content, &mime_type, &config_core)
        .map(Into::into)
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (items, config))]
pub fn batch_extract_files_sync(
    items: Vec<BatchFileItem>,
    config: ExtractionConfig,
) -> PyResult<Vec<ExtractionResult>> {
    let items_core: Vec<_> = items.into_iter().map(Into::into).collect();

    let config_core: kreuzberg::ExtractionConfig = config.into();

    kreuzberg::batch_extract_files_sync(items_core, &config_core)
        .map(|val| val.into_iter().map(Into::into).collect())
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (items, config))]
pub fn batch_extract_bytes_sync(
    items: Vec<BatchBytesItem>,
    config: ExtractionConfig,
) -> PyResult<Vec<ExtractionResult>> {
    let items_core: Vec<_> = items.into_iter().map(Into::into).collect();

    let config_core: kreuzberg::ExtractionConfig = config.into();

    kreuzberg::batch_extract_bytes_sync(items_core, &config_core)
        .map(|val| val.into_iter().map(Into::into).collect())
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (items, config))]
pub fn batch_extract_files<'py>(
    py: Python<'py>,
    items: Vec<BatchFileItem>,
    config: ExtractionConfig,
) -> PyResult<Bound<'py, PyAny>> {
    let items_core: Vec<_> = items.into_iter().map(Into::into).collect();

    let config_core: kreuzberg::ExtractionConfig = config.into();

    pyo3_async_runtimes::tokio::future_into_py(py, async move {
        let result = kreuzberg::batch_extract_files(items_core, &config_core)
            .await
            .map_err(|e| PyErr::new::<PyRuntimeError, _>(e.to_string()))?;

        Ok(result.into_iter().map(ExtractionResult::from).collect::<Vec<_>>())
    })
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (items, config))]
pub fn batch_extract_bytes<'py>(
    py: Python<'py>,
    items: Vec<BatchBytesItem>,
    config: ExtractionConfig,
) -> PyResult<Bound<'py, PyAny>> {
    let items_core: Vec<_> = items.into_iter().map(Into::into).collect();

    let config_core: kreuzberg::ExtractionConfig = config.into();

    pyo3_async_runtimes::tokio::future_into_py(py, async move {
        let result = kreuzberg::batch_extract_bytes(items_core, &config_core)
            .await
            .map_err(|e| PyErr::new::<PyRuntimeError, _>(e.to_string()))?;

        Ok(result.into_iter().map(ExtractionResult::from).collect::<Vec<_>>())
    })
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (content))]
pub fn detect_mime_type_from_bytes(content: Vec<u8>) -> PyResult<String> {
    kreuzberg::detect_mime_type_from_bytes(&content)
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (mime_type))]
pub fn get_extensions_for_mime(mime_type: String) -> PyResult<Vec<String>> {
    kreuzberg::get_extensions_for_mime(&mime_type).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn clear_embedding_backends() -> PyResult<()> {
    kreuzberg::clear_embedding_backends().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn list_embedding_backends() -> PyResult<Vec<String>> {
    kreuzberg::list_embedding_backends().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn list_document_extractors() -> PyResult<Vec<String>> {
    kreuzberg::list_document_extractors().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn clear_document_extractors() -> PyResult<()> {
    kreuzberg::clear_document_extractors().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn list_ocr_backends() -> PyResult<Vec<String>> {
    kreuzberg::list_ocr_backends().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn clear_ocr_backends() -> PyResult<()> {
    kreuzberg::clear_ocr_backends().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn list_post_processors() -> PyResult<Vec<String>> {
    kreuzberg::list_post_processors().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn clear_post_processors() -> PyResult<()> {
    kreuzberg::clear_post_processors().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn list_renderers() -> PyResult<Vec<String>> {
    kreuzberg::list_renderers().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn clear_renderers() -> PyResult<()> {
    kreuzberg::clear_renderers().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn list_validators() -> PyResult<Vec<String>> {
    kreuzberg::list_validators().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = ())]
pub fn clear_validators() -> PyResult<()> {
    kreuzberg::clear_validators().map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[pyfunction]
#[pyo3(signature = (a, b, opts))]
pub fn compare(a: ExtractionResult, b: ExtractionResult, opts: DiffOptions) -> ExtractionDiff {
    let a_core: kreuzberg::ExtractionResult = a.into();

    let b_core: kreuzberg::ExtractionResult = b.into();

    let opts_core: kreuzberg::DiffOptions = opts.into();

    kreuzberg::compare(&a_core, &b_core, &opts_core).into()
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (texts, config))]
pub fn embed_texts_async<'py>(
    py: Python<'py>,
    texts: Vec<String>,
    config: EmbeddingConfig,
) -> PyResult<Bound<'py, PyAny>> {
    let config_core: kreuzberg::EmbeddingConfig = config.into();

    pyo3_async_runtimes::tokio::future_into_py(py, async move {
        let result = kreuzberg::embed_texts_async(texts, &config_core)
            .await
            .map_err(|e| PyErr::new::<PyRuntimeError, _>(e.to_string()))?;

        Ok(result)
    })
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (pdf_bytes, page_index, dpi=None, password=None))]
pub fn render_pdf_page_to_png(
    pdf_bytes: Vec<u8>,
    page_index: usize,
    dpi: Option<i32>,
    password: Option<String>,
) -> PyResult<Vec<u8>> {
    kreuzberg::render_pdf_page_to_png(&pdf_bytes, page_index, dpi, password.as_deref())
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (path, check_exists))]
pub fn detect_mime_type(path: String, check_exists: bool) -> PyResult<String> {
    kreuzberg::detect_mime_type(path, check_exists)
        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[allow(clippy::missing_errors_doc)]
#[pyfunction]
#[pyo3(signature = (texts, config))]
pub fn embed_texts(texts: Vec<String>, config: EmbeddingConfig) -> PyResult<Vec<Vec<f32>>> {
    let config_core: kreuzberg::EmbeddingConfig = config.into();

    kreuzberg::embed_texts(texts, &config_core).map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
}

#[pyfunction]
#[pyo3(signature = (name))]
pub fn get_embedding_preset(name: String) -> Option<EmbeddingPreset> {
    kreuzberg::get_embedding_preset(&name).map(Into::into)
}

#[pyfunction]
#[pyo3(signature = ())]
pub fn list_embedding_presets() -> Vec<String> {
    kreuzberg::list_embedding_presets()
}

/// Wrapper that bridges a foreign Py object to the `OcrBackend` trait.
pub struct PyOcrBackendBridge {
    inner: Py<PyAny>,
    cached_name: String,
}

impl std::fmt::Debug for PyOcrBackendBridge {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PyOcrBackendBridge")
    }
}

impl PyOcrBackendBridge {
    /// Create a new bridge wrapping a Python object.
    ///
    /// Validates that the Python object provides all required methods.
    pub fn new(python_obj: Py<PyAny>) -> PyResult<Self> {
        Python::attach(|py| {
            let obj = python_obj.bind(py);
            if !obj.hasattr("process_image").unwrap_or(false) {
                return Err(pyo3::exceptions::PyAttributeError::new_err(
                    "Python object missing required method: process_image",
                ));
            }
            if !obj.hasattr("supports_language").unwrap_or(false) {
                return Err(pyo3::exceptions::PyAttributeError::new_err(
                    "Python object missing required method: supports_language",
                ));
            }
            if !obj.hasattr("backend_type").unwrap_or(false) {
                return Err(pyo3::exceptions::PyAttributeError::new_err(
                    "Python object missing required method: backend_type",
                ));
            }
            let cached_name: String = obj
                .call_method0("name")
                .and_then(|v| v.extract())
                .unwrap_or_else(|_| "unknown".to_string());

            Ok(Self {
                inner: python_obj,
                cached_name,
            })
        })
    }
}

impl kreuzberg::plugins::Plugin for PyOcrBackendBridge {
    fn name(&self) -> &str {
        &self.cached_name
    }

    fn version(&self) -> String {
        Python::attach(|py| {
            self.inner
                .bind(py)
                .call_method0("version")
                .and_then(|v| v.extract::<String>())
                .unwrap_or_default()
        })
    }

    fn initialize(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("initialize").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'initialize' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }

    fn shutdown(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("shutdown").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'shutdown' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }
}

#[async_trait::async_trait]
impl kreuzberg::OcrBackend for PyOcrBackendBridge {
    async fn process_image(
        &self,
        image_bytes: &[u8],
        config: &kreuzberg::OcrConfig,
    ) -> std::result::Result<kreuzberg::ExtractionResult, kreuzberg::KreuzbergError> {
        let python_obj = Python::attach(|py| self.inner.clone_ref(py));
        let cached_name = self.cached_name.clone();

        let image_bytes = image_bytes.to_vec();
        let config_json = serde_json::to_string(config).unwrap_or_default();

        tokio::task::spawn_blocking(move || {
            Python::attach(|py| {
                let obj = python_obj.bind(py);

                let py_result = obj
                    .call_method1(
                        "process_image",
                        (pyo3::types::PyBytes::new(py, &image_bytes), config_json.as_str()),
                    )
                    .map_err(|e| {
                        kreuzberg::KreuzbergError::Other(format!(
                            "Plugin '{}' method 'process_image' failed: {}",
                            cached_name, e
                        ))
                    })?;
                let json_val: String = py
                    .import("json")
                    .and_then(|m| m.call_method1("dumps", (py_result,)))
                    .and_then(|v| v.extract())
                    .map_err(|e| {
                        kreuzberg::KreuzbergError::Other(format!(
                            "Plugin '{}': JSON serialization failed: {}",
                            cached_name, e
                        ))
                    })?;
                serde_json::from_str::<kreuzberg::ExtractionResult>(&json_val).map_err(|e| {
                    kreuzberg::KreuzbergError::Other(format!("Plugin '{}': deserialization failed: {}", cached_name, e))
                })
            })
        })
        .await
        .map_err(|e| kreuzberg::KreuzbergError::Other(format!("spawn_blocking failed: {}", e)))
        .flatten()
    }

    fn supports_language(&self, lang: &str) -> bool {
        Python::attach(|py| {
            self.inner
                .bind(py)
                .call_method1("supports_language", (lang,))
                .and_then(|v| v.extract::<bool>())
                .unwrap_or_default()
        })
    }

    fn backend_type(&self) -> kreuzberg::OcrBackendType {
        Python::attach(|py| {
            self.inner
                .bind(py)
                .call_method0("backend_type")
                .and_then(|v| v.extract::<String>())
                .and_then(|s| {
                    serde_json::from_str::<kreuzberg::OcrBackendType>(&s)
                        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
                })
                .unwrap_or_default()
        })
    }
}

#[pyfunction]
pub fn register_ocr_backend(py: Python<'_>, backend: Py<PyAny>) -> PyResult<()> {
    let required_methods = ["process_image", "supports_language", "backend_type"];
    let obj = backend.bind(py);
    for method in &required_methods {
        if !obj.hasattr(*method)? {
            return Err(pyo3::exceptions::PyAttributeError::new_err(format!(
                "Backend missing required method: {}",
                method
            )));
        }
    }

    let wrapper = PyOcrBackendBridge::new(backend)?;
    let arc: Arc<dyn kreuzberg::OcrBackend> = Arc::new(wrapper);

    py.detach(|| {
        let registry = kreuzberg::plugins::registry::get_ocr_backend_registry();
        let mut registry = registry.write();
        registry
            .register(arc)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to register backend: {}", e)))
    })?;
    Ok(())
}

#[pyfunction]
#[pyo3(name = "unregister_ocr_backend")]
pub fn _alef_unregister_ocr_backend(py: Python<'_>, name: String) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::ocr_backend::unregister_ocr_backend(&name)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

#[pyfunction]
#[pyo3(name = "clear_ocr_backends")]
pub fn _alef_clear_ocr_backends(py: Python<'_>) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::ocr_backend::clear_ocr_backends()
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

/// Wrapper that bridges a foreign Py object to the `PostProcessor` trait.
pub struct PyPostProcessorBridge {
    inner: Py<PyAny>,
    cached_name: String,
}

impl std::fmt::Debug for PyPostProcessorBridge {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PyPostProcessorBridge")
    }
}

impl PyPostProcessorBridge {
    /// Create a new bridge wrapping a Python object.
    ///
    /// Validates that the Python object provides all required methods.
    pub fn new(python_obj: Py<PyAny>) -> PyResult<Self> {
        Python::attach(|py| {
            let obj = python_obj.bind(py);
            if !obj.hasattr("process").unwrap_or(false) {
                return Err(pyo3::exceptions::PyAttributeError::new_err(
                    "Python object missing required method: process",
                ));
            }
            if !obj.hasattr("processing_stage").unwrap_or(false) {
                return Err(pyo3::exceptions::PyAttributeError::new_err(
                    "Python object missing required method: processing_stage",
                ));
            }
            let cached_name: String = obj
                .call_method0("name")
                .and_then(|v| v.extract())
                .unwrap_or_else(|_| "unknown".to_string());

            Ok(Self {
                inner: python_obj,
                cached_name,
            })
        })
    }
}

impl kreuzberg::plugins::Plugin for PyPostProcessorBridge {
    fn name(&self) -> &str {
        &self.cached_name
    }

    fn version(&self) -> String {
        Python::attach(|py| {
            self.inner
                .bind(py)
                .call_method0("version")
                .and_then(|v| v.extract::<String>())
                .unwrap_or_default()
        })
    }

    fn initialize(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("initialize").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'initialize' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }

    fn shutdown(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("shutdown").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'shutdown' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }
}

#[async_trait::async_trait]
impl kreuzberg::PostProcessor for PyPostProcessorBridge {
    async fn process(
        &self,
        result: &mut kreuzberg::ExtractionResult,
        config: &kreuzberg::ExtractionConfig,
    ) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        let python_obj = Python::attach(|py| self.inner.clone_ref(py));
        let cached_name = self.cached_name.clone();

        let result_json = serde_json::to_string(result).unwrap_or_default();
        let config_json = serde_json::to_string(config).unwrap_or_default();

        tokio::task::spawn_blocking(move || {
            Python::attach(|py| {
                let obj = python_obj.bind(py);

                obj.call_method1("process", (result_json.as_str(), config_json.as_str()))
                    .map(|_| ())
                    .map_err(|e| {
                        kreuzberg::KreuzbergError::Other(format!(
                            "Plugin '{}' method 'process' failed: {}",
                            cached_name, e
                        ))
                    })
            })
        })
        .await
        .map_err(|e| kreuzberg::KreuzbergError::Other(format!("spawn_blocking failed: {}", e)))
        .flatten()
    }

    fn processing_stage(&self) -> kreuzberg::ProcessingStage {
        Python::attach(|py| {
            self.inner
                .bind(py)
                .call_method0("processing_stage")
                .and_then(|v| v.extract::<String>())
                .and_then(|s| {
                    serde_json::from_str::<kreuzberg::ProcessingStage>(&s)
                        .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
                })
                .unwrap_or_default()
        })
    }
}

#[pyfunction]
pub fn register_post_processor(py: Python<'_>, backend: Py<PyAny>) -> PyResult<()> {
    let required_methods = ["process", "processing_stage"];
    let obj = backend.bind(py);
    for method in &required_methods {
        if !obj.hasattr(*method)? {
            return Err(pyo3::exceptions::PyAttributeError::new_err(format!(
                "Backend missing required method: {}",
                method
            )));
        }
    }

    let wrapper = PyPostProcessorBridge::new(backend)?;
    let arc: Arc<dyn kreuzberg::PostProcessor> = Arc::new(wrapper);

    py.detach(|| {
        let registry = kreuzberg::plugins::registry::get_post_processor_registry();
        let mut registry = registry.write();
        registry
            .register(arc)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to register backend: {}", e)))
    })?;
    Ok(())
}

#[pyfunction]
#[pyo3(name = "unregister_post_processor")]
pub fn _alef_unregister_post_processor(py: Python<'_>, name: String) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::post_processor::unregister_post_processor(&name)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

#[pyfunction]
#[pyo3(name = "clear_post_processors")]
pub fn _alef_clear_post_processors(py: Python<'_>) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::post_processor::clear_post_processors()
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

/// Wrapper that bridges a foreign Py object to the `Validator` trait.
pub struct PyValidatorBridge {
    inner: Py<PyAny>,
    cached_name: String,
}

impl std::fmt::Debug for PyValidatorBridge {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PyValidatorBridge")
    }
}

impl PyValidatorBridge {
    /// Create a new bridge wrapping a Python object.
    ///
    /// Validates that the Python object provides all required methods.
    pub fn new(python_obj: Py<PyAny>) -> PyResult<Self> {
        Python::attach(|py| {
            let obj = python_obj.bind(py);
            if !obj.hasattr("validate").unwrap_or(false) {
                return Err(pyo3::exceptions::PyAttributeError::new_err(
                    "Python object missing required method: validate",
                ));
            }
            let cached_name: String = obj
                .call_method0("name")
                .and_then(|v| v.extract())
                .unwrap_or_else(|_| "unknown".to_string());

            Ok(Self {
                inner: python_obj,
                cached_name,
            })
        })
    }
}

impl kreuzberg::plugins::Plugin for PyValidatorBridge {
    fn name(&self) -> &str {
        &self.cached_name
    }

    fn version(&self) -> String {
        Python::attach(|py| {
            self.inner
                .bind(py)
                .call_method0("version")
                .and_then(|v| v.extract::<String>())
                .unwrap_or_default()
        })
    }

    fn initialize(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("initialize").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'initialize' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }

    fn shutdown(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("shutdown").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'shutdown' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }
}

#[async_trait::async_trait]
impl kreuzberg::Validator for PyValidatorBridge {
    async fn validate(
        &self,
        result: &kreuzberg::ExtractionResult,
        config: &kreuzberg::ExtractionConfig,
    ) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        let python_obj = Python::attach(|py| self.inner.clone_ref(py));
        let cached_name = self.cached_name.clone();

        let result_json = serde_json::to_string(result).unwrap_or_default();
        let config_json = serde_json::to_string(config).unwrap_or_default();

        tokio::task::spawn_blocking(move || {
            Python::attach(|py| {
                let obj = python_obj.bind(py);

                obj.call_method1("validate", (result_json.as_str(), config_json.as_str()))
                    .map(|_| ())
                    .map_err(|e| {
                        kreuzberg::KreuzbergError::Other(format!(
                            "Plugin '{}' method 'validate' failed: {}",
                            cached_name, e
                        ))
                    })
            })
        })
        .await
        .map_err(|e| kreuzberg::KreuzbergError::Other(format!("spawn_blocking failed: {}", e)))
        .flatten()
    }
}

#[pyfunction]
pub fn register_validator(py: Python<'_>, backend: Py<PyAny>) -> PyResult<()> {
    let required_methods = ["validate"];
    let obj = backend.bind(py);
    for method in &required_methods {
        if !obj.hasattr(*method)? {
            return Err(pyo3::exceptions::PyAttributeError::new_err(format!(
                "Backend missing required method: {}",
                method
            )));
        }
    }

    let wrapper = PyValidatorBridge::new(backend)?;
    let arc: Arc<dyn kreuzberg::Validator> = Arc::new(wrapper);

    py.detach(|| {
        let registry = kreuzberg::plugins::registry::get_validator_registry();
        let mut registry = registry.write();
        registry
            .register(arc)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to register backend: {}", e)))
    })?;
    Ok(())
}

#[pyfunction]
#[pyo3(name = "unregister_validator")]
pub fn _alef_unregister_validator(py: Python<'_>, name: String) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::validator::unregister_validator(&name)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

#[pyfunction]
#[pyo3(name = "clear_validators")]
pub fn _alef_clear_validators(py: Python<'_>) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::validator::clear_validators()
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

/// Wrapper that bridges a foreign Py object to the `EmbeddingBackend` trait.
pub struct PyEmbeddingBackendBridge {
    inner: Py<PyAny>,
    cached_name: String,
}

impl std::fmt::Debug for PyEmbeddingBackendBridge {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PyEmbeddingBackendBridge")
    }
}

impl PyEmbeddingBackendBridge {
    /// Create a new bridge wrapping a Python object.
    ///
    /// Validates that the Python object provides all required methods.
    pub fn new(python_obj: Py<PyAny>) -> PyResult<Self> {
        Python::attach(|py| {
            let obj = python_obj.bind(py);
            if !obj.hasattr("dimensions").unwrap_or(false) {
                return Err(pyo3::exceptions::PyAttributeError::new_err(
                    "Python object missing required method: dimensions",
                ));
            }
            if !obj.hasattr("embed").unwrap_or(false) {
                return Err(pyo3::exceptions::PyAttributeError::new_err(
                    "Python object missing required method: embed",
                ));
            }
            let cached_name: String = obj
                .call_method0("name")
                .and_then(|v| v.extract())
                .unwrap_or_else(|_| "unknown".to_string());

            Ok(Self {
                inner: python_obj,
                cached_name,
            })
        })
    }
}

impl kreuzberg::plugins::Plugin for PyEmbeddingBackendBridge {
    fn name(&self) -> &str {
        &self.cached_name
    }

    fn version(&self) -> String {
        Python::attach(|py| {
            self.inner
                .bind(py)
                .call_method0("version")
                .and_then(|v| v.extract::<String>())
                .unwrap_or_default()
        })
    }

    fn initialize(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("initialize").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'initialize' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }

    fn shutdown(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("shutdown").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'shutdown' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }
}

#[async_trait::async_trait]
impl kreuzberg::EmbeddingBackend for PyEmbeddingBackendBridge {
    fn dimensions(&self) -> usize {
        Python::attach(|py| {
            self.inner
                .bind(py)
                .call_method0("dimensions")
                .and_then(|v| v.extract::<usize>())
                .unwrap_or_default()
        })
    }

    async fn embed(&self, texts: Vec<String>) -> std::result::Result<Vec<Vec<f32>>, kreuzberg::KreuzbergError> {
        let python_obj = Python::attach(|py| self.inner.clone_ref(py));
        let cached_name = self.cached_name.clone();

        let texts = texts.clone();

        tokio::task::spawn_blocking(move || {
            Python::attach(|py| {
                let obj = python_obj.bind(py);

                obj.call_method1("embed", (texts,))
                    .and_then(|v| v.extract::<Vec<Vec<f32>>>())
                    .map_err(|e| {
                        kreuzberg::KreuzbergError::Other(format!(
                            "Plugin '{}' method 'embed' failed: {}",
                            cached_name, e
                        ))
                    })
            })
        })
        .await
        .map_err(|e| kreuzberg::KreuzbergError::Other(format!("spawn_blocking failed: {}", e)))
        .flatten()
    }
}

#[pyfunction]
pub fn register_embedding_backend(py: Python<'_>, backend: Py<PyAny>) -> PyResult<()> {
    let required_methods = ["dimensions", "embed"];
    let obj = backend.bind(py);
    for method in &required_methods {
        if !obj.hasattr(*method)? {
            return Err(pyo3::exceptions::PyAttributeError::new_err(format!(
                "Backend missing required method: {}",
                method
            )));
        }
    }

    let wrapper = PyEmbeddingBackendBridge::new(backend)?;
    let arc: Arc<dyn kreuzberg::EmbeddingBackend> = Arc::new(wrapper);

    py.detach(|| {
        let registry = kreuzberg::plugins::registry::get_embedding_backend_registry();
        let mut registry = registry.write();
        registry
            .register(arc)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to register backend: {}", e)))
    })?;
    Ok(())
}

#[pyfunction]
#[pyo3(name = "unregister_embedding_backend")]
pub fn _alef_unregister_embedding_backend(py: Python<'_>, name: String) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::embedding_backend::unregister_embedding_backend(&name)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

#[pyfunction]
#[pyo3(name = "clear_embedding_backends")]
pub fn _alef_clear_embedding_backends(py: Python<'_>) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::embedding_backend::clear_embedding_backends()
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

/// Wrapper that bridges a foreign Py object to the `DocumentExtractor` trait.
pub struct PyDocumentExtractorBridge {
    inner: Py<PyAny>,
    cached_name: String,
}

impl std::fmt::Debug for PyDocumentExtractorBridge {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PyDocumentExtractorBridge")
    }
}

impl PyDocumentExtractorBridge {
    /// Create a new bridge wrapping a Python object.
    ///
    /// Validates that the Python object provides all required methods.
    pub fn new(python_obj: Py<PyAny>) -> PyResult<Self> {
        Python::attach(|py| {
            let obj = python_obj.bind(py);
            if !obj.hasattr("extract_bytes").unwrap_or(false) {
                return Err(pyo3::exceptions::PyAttributeError::new_err(
                    "Python object missing required method: extract_bytes",
                ));
            }
            if !obj.hasattr("supported_mime_types").unwrap_or(false) {
                return Err(pyo3::exceptions::PyAttributeError::new_err(
                    "Python object missing required method: supported_mime_types",
                ));
            }
            let cached_name: String = obj
                .call_method0("name")
                .and_then(|v| v.extract())
                .unwrap_or_else(|_| "unknown".to_string());

            Ok(Self {
                inner: python_obj,
                cached_name,
            })
        })
    }
}

impl kreuzberg::plugins::Plugin for PyDocumentExtractorBridge {
    fn name(&self) -> &str {
        &self.cached_name
    }

    fn version(&self) -> String {
        Python::attach(|py| {
            self.inner
                .bind(py)
                .call_method0("version")
                .and_then(|v| v.extract::<String>())
                .unwrap_or_default()
        })
    }

    fn initialize(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("initialize").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'initialize' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }

    fn shutdown(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("shutdown").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'shutdown' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }
}

#[async_trait::async_trait]
impl kreuzberg::DocumentExtractor for PyDocumentExtractorBridge {
    async fn extract_bytes(
        &self,
        content: &[u8],
        mime_type: &str,
        config: &kreuzberg::ExtractionConfig,
    ) -> std::result::Result<kreuzberg::InternalDocument, kreuzberg::KreuzbergError> {
        let python_obj = Python::attach(|py| self.inner.clone_ref(py));
        let cached_name = self.cached_name.clone();

        let content = content.to_vec();
        let mime_type = mime_type.to_owned();
        let config_json = serde_json::to_string(config).unwrap_or_default();

        tokio::task::spawn_blocking(move || {
            Python::attach(|py| {
                let obj = python_obj.bind(py);

                let py_result = obj
                    .call_method1(
                        "extract_bytes",
                        (pyo3::types::PyBytes::new(py, &content), mime_type, config_json.as_str()),
                    )
                    .map_err(|e| {
                        kreuzberg::KreuzbergError::Other(format!(
                            "Plugin '{}' method 'extract_bytes' failed: {}",
                            cached_name, e
                        ))
                    })?;
                let json_val: String = py
                    .import("json")
                    .and_then(|m| m.call_method1("dumps", (py_result,)))
                    .and_then(|v| v.extract())
                    .map_err(|e| {
                        kreuzberg::KreuzbergError::Other(format!(
                            "Plugin '{}': JSON serialization failed: {}",
                            cached_name, e
                        ))
                    })?;
                serde_json::from_str::<kreuzberg::InternalDocument>(&json_val).map_err(|e| {
                    kreuzberg::KreuzbergError::Other(format!("Plugin '{}': deserialization failed: {}", cached_name, e))
                })
            })
        })
        .await
        .map_err(|e| kreuzberg::KreuzbergError::Other(format!("spawn_blocking failed: {}", e)))
        .flatten()
    }

    fn supported_mime_types(&self) -> &[&str] {
        let __types: Vec<String> = {
            Python::attach(|py| {
                self.inner
                    .bind(py)
                    .call_method0("supported_mime_types")
                    .and_then(|v| v.extract::<Vec<String>>())
                    .unwrap_or_default()
            })
        };
        let __strs: Vec<&'static str> = __types
            .into_iter()
            .map(|s| -> &'static str { Box::leak(s.into_boxed_str()) })
            .collect();
        Box::leak(__strs.into_boxed_slice())
    }
}

#[pyfunction]
pub fn register_document_extractor(py: Python<'_>, backend: Py<PyAny>) -> PyResult<()> {
    let required_methods = ["extract_bytes", "supported_mime_types"];
    let obj = backend.bind(py);
    for method in &required_methods {
        if !obj.hasattr(*method)? {
            return Err(pyo3::exceptions::PyAttributeError::new_err(format!(
                "Backend missing required method: {}",
                method
            )));
        }
    }

    let wrapper = PyDocumentExtractorBridge::new(backend)?;
    let arc: Arc<dyn kreuzberg::DocumentExtractor> = Arc::new(wrapper);

    py.detach(|| {
        let registry = kreuzberg::plugins::registry::get_document_extractor_registry();
        let mut registry = registry.write();
        registry
            .register(arc)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to register backend: {}", e)))
    })?;
    Ok(())
}

#[pyfunction]
#[pyo3(name = "unregister_document_extractor")]
pub fn _alef_unregister_document_extractor(py: Python<'_>, name: String) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::document_extractor::unregister_document_extractor(&name)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

#[pyfunction]
#[pyo3(name = "clear_document_extractors")]
pub fn _alef_clear_document_extractors(py: Python<'_>) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::document_extractor::clear_document_extractors()
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

/// Wrapper that bridges a foreign Py object to the `Renderer` trait.
pub struct PyRendererBridge {
    inner: Py<PyAny>,
    cached_name: String,
}

impl std::fmt::Debug for PyRendererBridge {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PyRendererBridge")
    }
}

impl PyRendererBridge {
    /// Create a new bridge wrapping a Python object.
    ///
    /// Validates that the Python object provides all required methods.
    pub fn new(python_obj: Py<PyAny>) -> PyResult<Self> {
        Python::attach(|py| {
            let obj = python_obj.bind(py);
            if !obj.hasattr("render").unwrap_or(false) {
                return Err(pyo3::exceptions::PyAttributeError::new_err(
                    "Python object missing required method: render",
                ));
            }
            let cached_name: String = obj
                .call_method0("name")
                .and_then(|v| v.extract())
                .unwrap_or_else(|_| "unknown".to_string());

            Ok(Self {
                inner: python_obj,
                cached_name,
            })
        })
    }
}

impl kreuzberg::plugins::Plugin for PyRendererBridge {
    fn name(&self) -> &str {
        &self.cached_name
    }

    fn version(&self) -> String {
        Python::attach(|py| {
            self.inner
                .bind(py)
                .call_method0("version")
                .and_then(|v| v.extract::<String>())
                .unwrap_or_default()
        })
    }

    fn initialize(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("initialize").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'initialize' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }

    fn shutdown(&self) -> std::result::Result<(), kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner.bind(py).call_method0("shutdown").map(|_| ()).map_err(|e| {
                kreuzberg::KreuzbergError::Other(format!(
                    "Plugin '{}' method 'shutdown' failed: {}",
                    self.cached_name, e
                ))
            })
        })
    }
}

impl kreuzberg::Renderer for PyRendererBridge {
    fn render(&self, doc: &kreuzberg::InternalDocument) -> std::result::Result<String, kreuzberg::KreuzbergError> {
        Python::attach(|py| {
            self.inner
                .bind(py)
                .call_method1("render", (serde_json::to_string(doc).unwrap_or_default(),))
                .and_then(|v| v.extract::<String>())
                .map_err(|e| {
                    kreuzberg::KreuzbergError::Other(format!(
                        "Plugin '{}' method 'render' failed: {}",
                        self.cached_name, e
                    ))
                })
        })
    }
}

#[pyfunction]
pub fn register_renderer(py: Python<'_>, backend: Py<PyAny>) -> PyResult<()> {
    let required_methods = ["render"];
    let obj = backend.bind(py);
    for method in &required_methods {
        if !obj.hasattr(*method)? {
            return Err(pyo3::exceptions::PyAttributeError::new_err(format!(
                "Backend missing required method: {}",
                method
            )));
        }
    }

    let wrapper = PyRendererBridge::new(backend)?;
    let arc: Arc<dyn kreuzberg::Renderer> = Arc::new(wrapper);

    py.detach(|| {
        let registry = kreuzberg::plugins::registry::get_renderer_registry();
        let mut registry = registry.write();
        registry
            .register(arc)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to register backend: {}", e)))
    })?;
    Ok(())
}

#[pyfunction]
#[pyo3(name = "unregister_renderer")]
pub fn _alef_unregister_renderer(py: Python<'_>, name: String) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::renderer::unregister_renderer(&name)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

#[pyfunction]
#[pyo3(name = "clear_renderers")]
pub fn _alef_clear_renderers(py: Python<'_>) -> PyResult<()> {
    py.detach(|| {
        kreuzberg::plugins::renderer::clear_renderers()
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("{}", e)))
    })
}

// Error types
pyo3::create_exception!(_kreuzberg, IoError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, ParsingError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, OcrError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, ValidationError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, CacheError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, ImageProcessingError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, SerializationError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, MissingDependencyError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, PluginError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, LockPoisonedError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, UnsupportedFormatError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, EmbeddingError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, KreuzbergTimeoutError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, CancelledError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, SecurityError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, OtherError, pyo3::exceptions::PyException);
pyo3::create_exception!(_kreuzberg, KreuzbergError, pyo3::exceptions::PyException);

/// Convert a `kreuzberg::KreuzbergError` error to a Python exception.
fn kreuzberg_error_to_py_err(e: kreuzberg::KreuzbergError) -> pyo3::PyErr {
    let msg = e.to_string();
    #[allow(unreachable_patterns)]
    match &e {
        kreuzberg::KreuzbergError::Io(..) => IoError::new_err(msg),
        kreuzberg::KreuzbergError::Parsing { .. } => ParsingError::new_err(msg),
        kreuzberg::KreuzbergError::Ocr { .. } => OcrError::new_err(msg),
        kreuzberg::KreuzbergError::Validation { .. } => ValidationError::new_err(msg),
        kreuzberg::KreuzbergError::Cache { .. } => CacheError::new_err(msg),
        kreuzberg::KreuzbergError::ImageProcessing { .. } => ImageProcessingError::new_err(msg),
        kreuzberg::KreuzbergError::Serialization { .. } => SerializationError::new_err(msg),
        kreuzberg::KreuzbergError::MissingDependency(..) => MissingDependencyError::new_err(msg),
        kreuzberg::KreuzbergError::Plugin { .. } => PluginError::new_err(msg),
        kreuzberg::KreuzbergError::LockPoisoned(..) => LockPoisonedError::new_err(msg),
        kreuzberg::KreuzbergError::UnsupportedFormat(..) => UnsupportedFormatError::new_err(msg),
        kreuzberg::KreuzbergError::Embedding { .. } => EmbeddingError::new_err(msg),
        kreuzberg::KreuzbergError::Timeout { .. } => KreuzbergTimeoutError::new_err(msg),
        kreuzberg::KreuzbergError::Cancelled => CancelledError::new_err(msg),
        kreuzberg::KreuzbergError::Security { .. } => SecurityError::new_err(msg),
        kreuzberg::KreuzbergError::Other(..) => OtherError::new_err(msg),
        _ => KreuzbergError::new_err(msg),
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::CacheStats> for CacheStats {
    fn from(val: kreuzberg::CacheStats) -> Self {
        Self {
            total_files: val.total_files,
            total_size_mb: val.total_size_mb,
            available_space_mb: val.available_space_mb,
            oldest_file_age_days: val.oldest_file_age_days,
            newest_file_age_days: val.newest_file_age_days,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<AccelerationConfig> for kreuzberg::AccelerationConfig {
    fn from(val: AccelerationConfig) -> Self {
        Self {
            provider: val.provider.into(),
            device_id: val.device_id,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::AccelerationConfig> for AccelerationConfig {
    fn from(val: kreuzberg::AccelerationConfig) -> Self {
        Self {
            provider: val.provider.into(),
            device_id: val.device_id,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ContentFilterConfig> for kreuzberg::ContentFilterConfig {
    fn from(val: ContentFilterConfig) -> Self {
        Self {
            include_headers: val.include_headers,
            include_footers: val.include_footers,
            strip_repeating_text: val.strip_repeating_text,
            include_watermarks: val.include_watermarks,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ContentFilterConfig> for ContentFilterConfig {
    fn from(val: kreuzberg::ContentFilterConfig) -> Self {
        Self {
            include_headers: val.include_headers,
            include_footers: val.include_footers,
            strip_repeating_text: val.strip_repeating_text,
            include_watermarks: val.include_watermarks,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<EmailConfig> for kreuzberg::EmailConfig {
    fn from(val: EmailConfig) -> Self {
        Self {
            msg_fallback_codepage: val.msg_fallback_codepage,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::EmailConfig> for EmailConfig {
    fn from(val: kreuzberg::EmailConfig) -> Self {
        Self {
            msg_fallback_codepage: val.msg_fallback_codepage,
        }
    }
}

#[allow(clippy::needless_update)]
#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ExtractionConfig> for kreuzberg::ExtractionConfig {
    fn from(val: ExtractionConfig) -> Self {
        Self {
            use_cache: val.use_cache,
            enable_quality_processing: val.enable_quality_processing,
            ocr: val.ocr.map(Into::into),
            force_ocr: val.force_ocr,
            force_ocr_pages: val.force_ocr_pages.map(|v| v.into_iter().collect()),
            disable_ocr: val.disable_ocr,
            chunking: val.chunking.map(Into::into),
            content_filter: val.content_filter.map(Into::into),
            images: val.images.map(Into::into),
            pdf_options: val.pdf_options.map(Into::into),
            token_reduction: val.token_reduction.map(Into::into),
            language_detection: val.language_detection.map(Into::into),
            pages: val.pages.map(Into::into),
            keywords: val.keywords.map(Into::into),
            postprocessor: val.postprocessor.map(Into::into),
            html_options: Default::default(),
            html_output: val.html_output.map(Into::into),
            extraction_timeout_secs: val.extraction_timeout_secs,
            max_concurrent_extractions: val.max_concurrent_extractions,
            result_format: val.result_format.into(),
            security_limits: val.security_limits.map(Into::into),
            max_embedded_file_bytes: val.max_embedded_file_bytes,
            output_format: val.output_format.into(),
            layout: val.layout.map(Into::into),
            use_layout_for_markdown: val.use_layout_for_markdown,
            include_document_structure: val.include_document_structure,
            acceleration: val.acceleration.map(Into::into),
            cache_namespace: val.cache_namespace,
            cache_ttl_secs: val.cache_ttl_secs,
            email: val.email.map(Into::into),
            concurrency: Default::default(),
            max_archive_depth: val.max_archive_depth,
            tree_sitter: val.tree_sitter.map(Into::into),
            structured_extraction: val.structured_extraction.map(Into::into),
            cancel_token: Default::default(),
            ..Default::default()
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ExtractionConfig> for ExtractionConfig {
    fn from(val: kreuzberg::ExtractionConfig) -> Self {
        Self {
            use_cache: val.use_cache,
            enable_quality_processing: val.enable_quality_processing,
            ocr: val.ocr.map(Into::into),
            force_ocr: val.force_ocr,
            force_ocr_pages: val.force_ocr_pages.map(|v| v.into_iter().collect()),
            disable_ocr: val.disable_ocr,
            chunking: val.chunking.map(Into::into),
            content_filter: val.content_filter.map(Into::into),
            images: val.images.map(Into::into),
            pdf_options: val.pdf_options.map(Into::into),
            token_reduction: val.token_reduction.map(Into::into),
            language_detection: val.language_detection.map(Into::into),
            pages: val.pages.map(Into::into),
            keywords: val.keywords.map(Into::into),
            postprocessor: val.postprocessor.map(Into::into),
            html_options: val.html_options.as_ref().map(|v| format!("{v:?}")),
            html_output: val.html_output.map(Into::into),
            extraction_timeout_secs: val.extraction_timeout_secs,
            max_concurrent_extractions: val.max_concurrent_extractions,
            result_format: val.result_format.into(),
            security_limits: val.security_limits.map(Into::into),
            max_embedded_file_bytes: val.max_embedded_file_bytes,
            output_format: val.output_format.into(),
            layout: val.layout.map(Into::into),
            use_layout_for_markdown: val.use_layout_for_markdown,
            include_document_structure: val.include_document_structure,
            acceleration: val.acceleration.map(Into::into),
            cache_namespace: val.cache_namespace,
            cache_ttl_secs: val.cache_ttl_secs,
            email: val.email.map(Into::into),
            concurrency: val.concurrency.as_ref().map(|v| format!("{v:?}")),
            max_archive_depth: val.max_archive_depth,
            tree_sitter: val.tree_sitter.map(Into::into),
            structured_extraction: val.structured_extraction.map(Into::into),
            cancel_token: val.cancel_token.as_ref().map(|v| format!("{v:?}")),
        }
    }
}

#[allow(clippy::needless_update)]
#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<FileExtractionConfig> for kreuzberg::FileExtractionConfig {
    fn from(val: FileExtractionConfig) -> Self {
        Self {
            enable_quality_processing: val.enable_quality_processing,
            ocr: val.ocr.map(Into::into),
            force_ocr: val.force_ocr,
            force_ocr_pages: val.force_ocr_pages.map(|v| v.into_iter().collect()),
            disable_ocr: val.disable_ocr,
            chunking: val.chunking.map(Into::into),
            content_filter: val.content_filter.map(Into::into),
            images: val.images.map(Into::into),
            pdf_options: val.pdf_options.map(Into::into),
            token_reduction: val.token_reduction.map(Into::into),
            language_detection: val.language_detection.map(Into::into),
            pages: val.pages.map(Into::into),
            keywords: val.keywords.map(Into::into),
            postprocessor: val.postprocessor.map(Into::into),
            html_options: Default::default(),
            result_format: val.result_format.map(Into::into),
            output_format: val.output_format.map(Into::into),
            include_document_structure: val.include_document_structure,
            layout: val.layout.map(Into::into),
            timeout_secs: val.timeout_secs,
            tree_sitter: val.tree_sitter.map(Into::into),
            structured_extraction: val.structured_extraction.map(Into::into),
            ..Default::default()
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::FileExtractionConfig> for FileExtractionConfig {
    fn from(val: kreuzberg::FileExtractionConfig) -> Self {
        Self {
            enable_quality_processing: val.enable_quality_processing,
            ocr: val.ocr.map(Into::into),
            force_ocr: val.force_ocr,
            force_ocr_pages: val.force_ocr_pages.map(|v| v.into_iter().collect()),
            disable_ocr: val.disable_ocr,
            chunking: val.chunking.map(Into::into),
            content_filter: val.content_filter.map(Into::into),
            images: val.images.map(Into::into),
            pdf_options: val.pdf_options.map(Into::into),
            token_reduction: val.token_reduction.map(Into::into),
            language_detection: val.language_detection.map(Into::into),
            pages: val.pages.map(Into::into),
            keywords: val.keywords.map(Into::into),
            postprocessor: val.postprocessor.map(Into::into),
            html_options: val.html_options.as_ref().map(|v| format!("{v:?}")),
            result_format: val.result_format.map(Into::into),
            output_format: val.output_format.map(Into::into),
            include_document_structure: val.include_document_structure,
            layout: val.layout.map(Into::into),
            timeout_secs: val.timeout_secs,
            tree_sitter: val.tree_sitter.map(Into::into),
            structured_extraction: val.structured_extraction.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<BatchBytesItem> for kreuzberg::BatchBytesItem {
    fn from(val: BatchBytesItem) -> Self {
        Self {
            content: val.content.to_vec().into(),
            mime_type: val.mime_type,
            config: val.config.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::BatchBytesItem> for BatchBytesItem {
    fn from(val: kreuzberg::BatchBytesItem) -> Self {
        Self {
            content: val.content.to_vec().into(),
            mime_type: val.mime_type,
            config: val.config.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<BatchFileItem> for kreuzberg::BatchFileItem {
    fn from(val: BatchFileItem) -> Self {
        Self {
            path: val.path.into(),
            config: val.config.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::BatchFileItem> for BatchFileItem {
    fn from(val: kreuzberg::BatchFileItem) -> Self {
        Self {
            path: val.path.to_string_lossy().to_string(),
            config: val.config.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ImageExtractionConfig> for kreuzberg::ImageExtractionConfig {
    fn from(val: ImageExtractionConfig) -> Self {
        Self {
            extract_images: val.extract_images,
            target_dpi: val.target_dpi,
            max_image_dimension: val.max_image_dimension,
            inject_placeholders: val.inject_placeholders,
            auto_adjust_dpi: val.auto_adjust_dpi,
            min_dpi: val.min_dpi,
            max_dpi: val.max_dpi,
            max_images_per_page: val.max_images_per_page,
            classify: val.classify,
            include_page_rasters: val.include_page_rasters,
            run_ocr_on_images: val.run_ocr_on_images,
            ocr_text_only: val.ocr_text_only,
            append_ocr_text: val.append_ocr_text,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ImageExtractionConfig> for ImageExtractionConfig {
    fn from(val: kreuzberg::ImageExtractionConfig) -> Self {
        Self {
            extract_images: val.extract_images,
            target_dpi: val.target_dpi,
            max_image_dimension: val.max_image_dimension,
            inject_placeholders: val.inject_placeholders,
            auto_adjust_dpi: val.auto_adjust_dpi,
            min_dpi: val.min_dpi,
            max_dpi: val.max_dpi,
            max_images_per_page: val.max_images_per_page,
            classify: val.classify,
            include_page_rasters: val.include_page_rasters,
            run_ocr_on_images: val.run_ocr_on_images,
            ocr_text_only: val.ocr_text_only,
            append_ocr_text: val.append_ocr_text,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<TokenReductionOptions> for kreuzberg::TokenReductionOptions {
    fn from(val: TokenReductionOptions) -> Self {
        Self {
            mode: val.mode,
            preserve_important_words: val.preserve_important_words,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::TokenReductionOptions> for TokenReductionOptions {
    fn from(val: kreuzberg::TokenReductionOptions) -> Self {
        Self {
            mode: val.mode,
            preserve_important_words: val.preserve_important_words,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<LanguageDetectionConfig> for kreuzberg::LanguageDetectionConfig {
    fn from(val: LanguageDetectionConfig) -> Self {
        Self {
            enabled: val.enabled,
            min_confidence: val.min_confidence,
            detect_multiple: val.detect_multiple,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::LanguageDetectionConfig> for LanguageDetectionConfig {
    fn from(val: kreuzberg::LanguageDetectionConfig) -> Self {
        Self {
            enabled: val.enabled,
            min_confidence: val.min_confidence,
            detect_multiple: val.detect_multiple,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<HtmlOutputConfig> for kreuzberg::HtmlOutputConfig {
    fn from(val: HtmlOutputConfig) -> Self {
        Self {
            css: val.css,
            css_file: val.css_file.map(Into::into),
            theme: val.theme.into(),
            class_prefix: val.class_prefix,
            embed_css: val.embed_css,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::HtmlOutputConfig> for HtmlOutputConfig {
    fn from(val: kreuzberg::HtmlOutputConfig) -> Self {
        Self {
            css: val.css,
            css_file: val.css_file.map(|p| p.to_string_lossy().to_string()),
            theme: val.theme.into(),
            class_prefix: val.class_prefix,
            embed_css: val.embed_css,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<LayoutDetectionConfig> for kreuzberg::LayoutDetectionConfig {
    fn from(val: LayoutDetectionConfig) -> Self {
        Self {
            confidence_threshold: val.confidence_threshold,
            apply_heuristics: val.apply_heuristics,
            table_model: val.table_model.into(),
            acceleration: val.acceleration.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::LayoutDetectionConfig> for LayoutDetectionConfig {
    fn from(val: kreuzberg::LayoutDetectionConfig) -> Self {
        Self {
            confidence_threshold: val.confidence_threshold,
            apply_heuristics: val.apply_heuristics,
            table_model: val.table_model.into(),
            acceleration: val.acceleration.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<LlmConfig> for kreuzberg::LlmConfig {
    fn from(val: LlmConfig) -> Self {
        Self {
            model: val.model,
            api_key: val.api_key,
            base_url: val.base_url,
            timeout_secs: val.timeout_secs,
            max_retries: val.max_retries,
            temperature: val.temperature,
            max_tokens: val.max_tokens,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::LlmConfig> for LlmConfig {
    fn from(val: kreuzberg::LlmConfig) -> Self {
        Self {
            model: val.model,
            api_key: val.api_key,
            base_url: val.base_url,
            timeout_secs: val.timeout_secs,
            max_retries: val.max_retries,
            temperature: val.temperature,
            max_tokens: val.max_tokens,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<StructuredExtractionConfig> for kreuzberg::StructuredExtractionConfig {
    fn from(val: StructuredExtractionConfig) -> Self {
        Self {
            schema: serde_json::from_str(&val.schema).unwrap_or_default(),
            schema_name: val.schema_name,
            schema_description: val.schema_description,
            strict: val.strict,
            prompt: val.prompt,
            llm: val.llm.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::StructuredExtractionConfig> for StructuredExtractionConfig {
    fn from(val: kreuzberg::StructuredExtractionConfig) -> Self {
        Self {
            schema: val.schema.to_string(),
            schema_name: val.schema_name,
            schema_description: val.schema_description,
            strict: val.strict,
            prompt: val.prompt,
            llm: val.llm.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrQualityThresholds> for kreuzberg::OcrQualityThresholds {
    fn from(val: OcrQualityThresholds) -> Self {
        Self {
            min_total_non_whitespace: val.min_total_non_whitespace,
            min_non_whitespace_per_page: val.min_non_whitespace_per_page,
            min_meaningful_word_len: val.min_meaningful_word_len,
            min_meaningful_words: val.min_meaningful_words,
            min_alnum_ratio: val.min_alnum_ratio,
            min_garbage_chars: val.min_garbage_chars,
            max_fragmented_word_ratio: val.max_fragmented_word_ratio,
            critical_fragmented_word_ratio: val.critical_fragmented_word_ratio,
            min_avg_word_length: val.min_avg_word_length,
            min_words_for_avg_length_check: val.min_words_for_avg_length_check,
            min_consecutive_repeat_ratio: val.min_consecutive_repeat_ratio,
            min_words_for_repeat_check: val.min_words_for_repeat_check,
            substantive_min_chars: val.substantive_min_chars,
            non_text_min_chars: val.non_text_min_chars,
            alnum_ws_ratio_threshold: val.alnum_ws_ratio_threshold,
            pipeline_min_quality: val.pipeline_min_quality,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrQualityThresholds> for OcrQualityThresholds {
    fn from(val: kreuzberg::OcrQualityThresholds) -> Self {
        Self {
            min_total_non_whitespace: val.min_total_non_whitespace,
            min_non_whitespace_per_page: val.min_non_whitespace_per_page,
            min_meaningful_word_len: val.min_meaningful_word_len,
            min_meaningful_words: val.min_meaningful_words,
            min_alnum_ratio: val.min_alnum_ratio,
            min_garbage_chars: val.min_garbage_chars,
            max_fragmented_word_ratio: val.max_fragmented_word_ratio,
            critical_fragmented_word_ratio: val.critical_fragmented_word_ratio,
            min_avg_word_length: val.min_avg_word_length,
            min_words_for_avg_length_check: val.min_words_for_avg_length_check,
            min_consecutive_repeat_ratio: val.min_consecutive_repeat_ratio,
            min_words_for_repeat_check: val.min_words_for_repeat_check,
            substantive_min_chars: val.substantive_min_chars,
            non_text_min_chars: val.non_text_min_chars,
            alnum_ws_ratio_threshold: val.alnum_ws_ratio_threshold,
            pipeline_min_quality: val.pipeline_min_quality,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrPipelineStage> for kreuzberg::OcrPipelineStage {
    fn from(val: OcrPipelineStage) -> Self {
        Self {
            backend: val.backend,
            priority: val.priority,
            language: val.language,
            tesseract_config: val.tesseract_config.map(Into::into),
            paddle_ocr_config: val
                .paddle_ocr_config
                .as_ref()
                .and_then(|s| serde_json::from_str(s).ok()),
            vlm_config: val.vlm_config.map(Into::into),
            backend_options: val.backend_options.as_ref().and_then(|s| serde_json::from_str(s).ok()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrPipelineStage> for OcrPipelineStage {
    fn from(val: kreuzberg::OcrPipelineStage) -> Self {
        Self {
            backend: val.backend,
            priority: val.priority,
            language: val.language,
            tesseract_config: val.tesseract_config.map(Into::into),
            paddle_ocr_config: val.paddle_ocr_config.as_ref().map(ToString::to_string),
            vlm_config: val.vlm_config.map(Into::into),
            backend_options: val.backend_options.as_ref().map(ToString::to_string),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrPipelineConfig> for kreuzberg::OcrPipelineConfig {
    fn from(val: OcrPipelineConfig) -> Self {
        Self {
            stages: val.stages.into_iter().map(Into::into).collect(),
            quality_thresholds: val.quality_thresholds.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrPipelineConfig> for OcrPipelineConfig {
    fn from(val: kreuzberg::OcrPipelineConfig) -> Self {
        Self {
            stages: val.stages.into_iter().map(Into::into).collect(),
            quality_thresholds: val.quality_thresholds.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrConfig> for kreuzberg::OcrConfig {
    fn from(val: OcrConfig) -> Self {
        Self {
            enabled: val.enabled,
            backend: val.backend,
            language: val.language,
            tesseract_config: val.tesseract_config.map(Into::into),
            output_format: val.output_format.map(Into::into),
            paddle_ocr_config: val
                .paddle_ocr_config
                .as_ref()
                .and_then(|s| serde_json::from_str(s).ok()),
            backend_options: val.backend_options.as_ref().and_then(|s| serde_json::from_str(s).ok()),
            element_config: val.element_config.map(Into::into),
            quality_thresholds: val.quality_thresholds.map(Into::into),
            pipeline: val.pipeline.map(Into::into),
            auto_rotate: val.auto_rotate,
            vlm_config: val.vlm_config.map(Into::into),
            vlm_prompt: val.vlm_prompt,
            acceleration: val.acceleration.map(Into::into),
            tessdata_bytes: val
                .tessdata_bytes
                .map(|m| m.into_iter().map(|(k, v)| (k, v.to_vec().into())).collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrConfig> for OcrConfig {
    fn from(val: kreuzberg::OcrConfig) -> Self {
        Self {
            enabled: val.enabled,
            backend: val.backend,
            language: val.language,
            tesseract_config: val.tesseract_config.map(Into::into),
            output_format: val.output_format.map(Into::into),
            paddle_ocr_config: val.paddle_ocr_config.as_ref().map(ToString::to_string),
            backend_options: val.backend_options.as_ref().map(ToString::to_string),
            element_config: val.element_config.map(Into::into),
            quality_thresholds: val.quality_thresholds.map(Into::into),
            pipeline: val.pipeline.map(Into::into),
            auto_rotate: val.auto_rotate,
            vlm_config: val.vlm_config.map(Into::into),
            vlm_prompt: val.vlm_prompt,
            acceleration: val.acceleration.map(Into::into),
            tessdata_bytes: val
                .tessdata_bytes
                .map(|m| m.into_iter().map(|(k, v)| (k, v.to_vec().into())).collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PageConfig> for kreuzberg::PageConfig {
    fn from(val: PageConfig) -> Self {
        Self {
            extract_pages: val.extract_pages,
            insert_page_markers: val.insert_page_markers,
            marker_format: val.marker_format,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PageConfig> for PageConfig {
    fn from(val: kreuzberg::PageConfig) -> Self {
        Self {
            extract_pages: val.extract_pages,
            insert_page_markers: val.insert_page_markers,
            marker_format: val.marker_format,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PdfConfig> for kreuzberg::PdfConfig {
    fn from(val: PdfConfig) -> Self {
        Self {
            extract_images: val.extract_images,
            extract_tables: val.extract_tables,
            passwords: val.passwords.map(|v| v.into_iter().collect()),
            extract_metadata: val.extract_metadata,
            hierarchy: val.hierarchy.map(Into::into),
            extract_annotations: val.extract_annotations,
            top_margin_fraction: val.top_margin_fraction,
            bottom_margin_fraction: val.bottom_margin_fraction,
            allow_single_column_tables: val.allow_single_column_tables,
            ocr_inline_images: val.ocr_inline_images,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PdfConfig> for PdfConfig {
    fn from(val: kreuzberg::PdfConfig) -> Self {
        Self {
            extract_images: val.extract_images,
            extract_tables: val.extract_tables,
            passwords: val.passwords.map(|v| v.into_iter().collect()),
            extract_metadata: val.extract_metadata,
            hierarchy: val.hierarchy.map(Into::into),
            extract_annotations: val.extract_annotations,
            top_margin_fraction: val.top_margin_fraction,
            bottom_margin_fraction: val.bottom_margin_fraction,
            allow_single_column_tables: val.allow_single_column_tables,
            ocr_inline_images: val.ocr_inline_images,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<HierarchyConfig> for kreuzberg::HierarchyConfig {
    fn from(val: HierarchyConfig) -> Self {
        Self {
            enabled: val.enabled,
            k_clusters: val.k_clusters,
            include_bbox: val.include_bbox,
            ocr_coverage_threshold: val.ocr_coverage_threshold,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::HierarchyConfig> for HierarchyConfig {
    fn from(val: kreuzberg::HierarchyConfig) -> Self {
        Self {
            enabled: val.enabled,
            k_clusters: val.k_clusters,
            include_bbox: val.include_bbox,
            ocr_coverage_threshold: val.ocr_coverage_threshold,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PostProcessorConfig> for kreuzberg::PostProcessorConfig {
    fn from(val: PostProcessorConfig) -> Self {
        Self {
            enabled: val.enabled,
            enabled_processors: val.enabled_processors.map(|v| v.into_iter().collect()),
            disabled_processors: val.disabled_processors.map(|v| v.into_iter().collect()),
            enabled_set: val.enabled_set.map(|v| v.into_iter().collect()),
            disabled_set: val.disabled_set.map(|v| v.into_iter().collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PostProcessorConfig> for PostProcessorConfig {
    fn from(val: kreuzberg::PostProcessorConfig) -> Self {
        Self {
            enabled: val.enabled,
            enabled_processors: val.enabled_processors.map(|v| v.into_iter().collect()),
            disabled_processors: val.disabled_processors.map(|v| v.into_iter().collect()),
            enabled_set: val.enabled_set.map(|v| v.into_iter().collect()),
            disabled_set: val.disabled_set.map(|v| v.into_iter().collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ChunkingConfig> for kreuzberg::ChunkingConfig {
    fn from(val: ChunkingConfig) -> Self {
        Self {
            max_characters: val.max_characters,
            overlap: val.overlap,
            trim: val.trim,
            chunker_type: val.chunker_type.into(),
            embedding: val.embedding.map(Into::into),
            preset: val.preset,
            sizing: val.sizing.into(),
            prepend_heading_context: val.prepend_heading_context,
            topic_threshold: val.topic_threshold,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ChunkingConfig> for ChunkingConfig {
    fn from(val: kreuzberg::ChunkingConfig) -> Self {
        Self {
            max_characters: val.max_characters,
            overlap: val.overlap,
            trim: val.trim,
            chunker_type: val.chunker_type.into(),
            embedding: val.embedding.map(Into::into),
            preset: val.preset,
            sizing: val.sizing.into(),
            prepend_heading_context: val.prepend_heading_context,
            topic_threshold: val.topic_threshold,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<EmbeddingConfig> for kreuzberg::EmbeddingConfig {
    fn from(val: EmbeddingConfig) -> Self {
        Self {
            model: val.model.into(),
            normalize: val.normalize,
            batch_size: val.batch_size,
            show_download_progress: val.show_download_progress,
            cache_dir: val.cache_dir.map(Into::into),
            acceleration: val.acceleration.map(Into::into),
            max_embed_duration_secs: val.max_embed_duration_secs,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::EmbeddingConfig> for EmbeddingConfig {
    fn from(val: kreuzberg::EmbeddingConfig) -> Self {
        Self {
            model: val.model.into(),
            normalize: val.normalize,
            batch_size: val.batch_size,
            show_download_progress: val.show_download_progress,
            cache_dir: val.cache_dir.map(|p| p.to_string_lossy().to_string()),
            acceleration: val.acceleration.map(Into::into),
            max_embed_duration_secs: val.max_embed_duration_secs,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<TreeSitterConfig> for kreuzberg::TreeSitterConfig {
    fn from(val: TreeSitterConfig) -> Self {
        Self {
            enabled: val.enabled,
            cache_dir: val.cache_dir.map(Into::into),
            languages: val.languages.map(|v| v.into_iter().collect()),
            groups: val.groups.map(|v| v.into_iter().collect()),
            process: val.process.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::TreeSitterConfig> for TreeSitterConfig {
    fn from(val: kreuzberg::TreeSitterConfig) -> Self {
        Self {
            enabled: val.enabled,
            cache_dir: val.cache_dir.map(|p| p.to_string_lossy().to_string()),
            languages: val.languages.map(|v| v.into_iter().collect()),
            groups: val.groups.map(|v| v.into_iter().collect()),
            process: val.process.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<TreeSitterProcessConfig> for kreuzberg::TreeSitterProcessConfig {
    fn from(val: TreeSitterProcessConfig) -> Self {
        Self {
            structure: val.structure,
            imports: val.imports,
            exports: val.exports,
            comments: val.comments,
            docstrings: val.docstrings,
            symbols: val.symbols,
            diagnostics: val.diagnostics,
            chunk_max_size: val.chunk_max_size,
            content_mode: val.content_mode.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::TreeSitterProcessConfig> for TreeSitterProcessConfig {
    fn from(val: kreuzberg::TreeSitterProcessConfig) -> Self {
        Self {
            structure: val.structure,
            imports: val.imports,
            exports: val.exports,
            comments: val.comments,
            docstrings: val.docstrings,
            symbols: val.symbols,
            diagnostics: val.diagnostics,
            chunk_max_size: val.chunk_max_size,
            content_mode: val.content_mode.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::SupportedFormat> for SupportedFormat {
    fn from(val: kreuzberg::SupportedFormat) -> Self {
        Self {
            extension: val.extension,
            mime_type: val.mime_type,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ServerConfig> for kreuzberg::ServerConfig {
    fn from(val: ServerConfig) -> Self {
        Self {
            host: val.host,
            port: val.port,
            cors_origins: val.cors_origins.into_iter().collect(),
            max_request_body_bytes: val.max_request_body_bytes,
            max_multipart_field_bytes: val.max_multipart_field_bytes,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ServerConfig> for ServerConfig {
    fn from(val: kreuzberg::ServerConfig) -> Self {
        Self {
            host: val.host,
            port: val.port,
            cors_origins: val.cors_origins.into_iter().collect(),
            max_request_body_bytes: val.max_request_body_bytes,
            max_multipart_field_bytes: val.max_multipart_field_bytes,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::extraction::structured::StructuredDataResult> for StructuredDataResult {
    fn from(val: kreuzberg::extraction::structured::StructuredDataResult) -> Self {
        Self {
            content: val.content,
            format: val.format.to_string(),
            metadata: val.metadata.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            text_fields: val.text_fields.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DocxAppProperties> for kreuzberg::DocxAppProperties {
    fn from(val: DocxAppProperties) -> Self {
        Self {
            application: val.application,
            app_version: val.app_version,
            template: val.template,
            total_time: val.total_time,
            pages: val.pages,
            words: val.words,
            characters: val.characters,
            characters_with_spaces: val.characters_with_spaces,
            lines: val.lines,
            paragraphs: val.paragraphs,
            company: val.company,
            doc_security: val.doc_security,
            scale_crop: val.scale_crop,
            links_up_to_date: val.links_up_to_date,
            shared_doc: val.shared_doc,
            hyperlinks_changed: val.hyperlinks_changed,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DocxAppProperties> for DocxAppProperties {
    fn from(val: kreuzberg::DocxAppProperties) -> Self {
        Self {
            application: val.application,
            app_version: val.app_version,
            template: val.template,
            total_time: val.total_time,
            pages: val.pages,
            words: val.words,
            characters: val.characters,
            characters_with_spaces: val.characters_with_spaces,
            lines: val.lines,
            paragraphs: val.paragraphs,
            company: val.company,
            doc_security: val.doc_security,
            scale_crop: val.scale_crop,
            links_up_to_date: val.links_up_to_date,
            shared_doc: val.shared_doc,
            hyperlinks_changed: val.hyperlinks_changed,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::extraction::office_metadata::app_properties::XlsxAppProperties> for XlsxAppProperties {
    fn from(val: kreuzberg::extraction::office_metadata::app_properties::XlsxAppProperties) -> Self {
        Self {
            application: val.application,
            app_version: val.app_version,
            doc_security: val.doc_security,
            scale_crop: val.scale_crop,
            links_up_to_date: val.links_up_to_date,
            shared_doc: val.shared_doc,
            hyperlinks_changed: val.hyperlinks_changed,
            company: val.company,
            worksheet_names: val.worksheet_names.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::extraction::office_metadata::app_properties::PptxAppProperties> for PptxAppProperties {
    fn from(val: kreuzberg::extraction::office_metadata::app_properties::PptxAppProperties) -> Self {
        Self {
            application: val.application,
            app_version: val.app_version,
            total_time: val.total_time,
            company: val.company,
            doc_security: val.doc_security,
            scale_crop: val.scale_crop,
            links_up_to_date: val.links_up_to_date,
            shared_doc: val.shared_doc,
            hyperlinks_changed: val.hyperlinks_changed,
            slides: val.slides,
            notes: val.notes,
            hidden_slides: val.hidden_slides,
            multimedia_clips: val.multimedia_clips,
            presentation_format: val.presentation_format,
            slide_titles: val.slide_titles.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<CoreProperties> for kreuzberg::CoreProperties {
    fn from(val: CoreProperties) -> Self {
        Self {
            title: val.title,
            subject: val.subject,
            creator: val.creator,
            keywords: val.keywords,
            description: val.description,
            last_modified_by: val.last_modified_by,
            revision: val.revision,
            created: val.created,
            modified: val.modified,
            category: val.category,
            content_status: val.content_status,
            language: val.language,
            identifier: val.identifier,
            version: val.version,
            last_printed: val.last_printed,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::CoreProperties> for CoreProperties {
    fn from(val: kreuzberg::CoreProperties) -> Self {
        Self {
            title: val.title,
            subject: val.subject,
            creator: val.creator,
            keywords: val.keywords,
            description: val.description,
            last_modified_by: val.last_modified_by,
            revision: val.revision,
            created: val.created,
            modified: val.modified,
            category: val.category,
            content_status: val.content_status,
            language: val.language,
            identifier: val.identifier,
            version: val.version,
            last_printed: val.last_printed,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<SecurityLimits> for kreuzberg::SecurityLimits {
    fn from(val: SecurityLimits) -> Self {
        Self {
            max_archive_size: val.max_archive_size,
            max_compression_ratio: val.max_compression_ratio,
            max_files_in_archive: val.max_files_in_archive,
            max_nesting_depth: val.max_nesting_depth,
            max_entity_length: val.max_entity_length,
            max_content_size: val.max_content_size,
            max_iterations: val.max_iterations,
            max_xml_depth: val.max_xml_depth,
            max_table_cells: val.max_table_cells,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::SecurityLimits> for SecurityLimits {
    fn from(val: kreuzberg::SecurityLimits) -> Self {
        Self {
            max_archive_size: val.max_archive_size,
            max_compression_ratio: val.max_compression_ratio,
            max_files_in_archive: val.max_files_in_archive,
            max_nesting_depth: val.max_nesting_depth,
            max_entity_length: val.max_entity_length,
            max_content_size: val.max_content_size,
            max_iterations: val.max_iterations,
            max_xml_depth: val.max_xml_depth,
            max_table_cells: val.max_table_cells,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<TokenReductionConfig> for kreuzberg::TokenReductionConfig {
    fn from(val: TokenReductionConfig) -> Self {
        Self {
            level: val.level.into(),
            language_hint: val.language_hint,
            preserve_markdown: val.preserve_markdown,
            preserve_code: val.preserve_code,
            semantic_threshold: val.semantic_threshold,
            enable_parallel: val.enable_parallel,
            use_simd: val.use_simd,
            custom_stopwords: val.custom_stopwords.map(|m| m.into_iter().collect()),
            preserve_patterns: val.preserve_patterns.into_iter().collect(),
            target_reduction: val.target_reduction,
            enable_semantic_clustering: val.enable_semantic_clustering,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::TokenReductionConfig> for TokenReductionConfig {
    fn from(val: kreuzberg::TokenReductionConfig) -> Self {
        Self {
            level: val.level.into(),
            language_hint: val.language_hint,
            preserve_markdown: val.preserve_markdown,
            preserve_code: val.preserve_code,
            semantic_threshold: val.semantic_threshold,
            enable_parallel: val.enable_parallel,
            use_simd: val.use_simd,
            custom_stopwords: val.custom_stopwords.map(|m| m.into_iter().collect()),
            preserve_patterns: val.preserve_patterns.into_iter().collect(),
            target_reduction: val.target_reduction,
            enable_semantic_clustering: val.enable_semantic_clustering,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PdfAnnotation> for kreuzberg::PdfAnnotation {
    fn from(val: PdfAnnotation) -> Self {
        Self {
            annotation_type: val.annotation_type.into(),
            content: val.content,
            page_number: val.page_number,
            bounding_box: val.bounding_box.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PdfAnnotation> for PdfAnnotation {
    fn from(val: kreuzberg::PdfAnnotation) -> Self {
        Self {
            annotation_type: val.annotation_type.into(),
            content: val.content,
            page_number: val.page_number,
            bounding_box: val.bounding_box.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DjotContent> for kreuzberg::DjotContent {
    fn from(val: DjotContent) -> Self {
        Self {
            plain_text: val.plain_text,
            blocks: val.blocks.into_iter().map(Into::into).collect(),
            metadata: val.metadata.into(),
            tables: val.tables.into_iter().map(Into::into).collect(),
            images: val.images.into_iter().map(Into::into).collect(),
            links: val.links.into_iter().map(Into::into).collect(),
            footnotes: val.footnotes.into_iter().map(Into::into).collect(),
            attributes: Default::default(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DjotContent> for DjotContent {
    fn from(val: kreuzberg::DjotContent) -> Self {
        Self {
            plain_text: val.plain_text,
            blocks: val.blocks.into_iter().map(Into::into).collect(),
            metadata: val.metadata.into(),
            tables: val.tables.into_iter().map(Into::into).collect(),
            images: val.images.into_iter().map(Into::into).collect(),
            links: val.links.into_iter().map(Into::into).collect(),
            footnotes: val.footnotes.into_iter().map(Into::into).collect(),
            attributes: val.attributes.iter().map(|i| format!("{:?}", i)).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<FormattedBlock> for kreuzberg::FormattedBlock {
    fn from(val: FormattedBlock) -> Self {
        Self {
            block_type: val.block_type.into(),
            level: val.level,
            inline_content: val.inline_content.into_iter().map(Into::into).collect(),
            attributes: Default::default(),
            language: val.language,
            code: val.code,
            children: val.children.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::FormattedBlock> for FormattedBlock {
    fn from(val: kreuzberg::FormattedBlock) -> Self {
        Self {
            block_type: val.block_type.into(),
            level: val.level,
            inline_content: val.inline_content.into_iter().map(Into::into).collect(),
            attributes: val.attributes.as_ref().map(|v| format!("{v:?}")),
            language: val.language,
            code: val.code,
            children: val.children.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<InlineElement> for kreuzberg::InlineElement {
    fn from(val: InlineElement) -> Self {
        Self {
            element_type: val.element_type.into(),
            content: val.content,
            attributes: Default::default(),
            metadata: val
                .metadata
                .map(|m| m.into_iter().map(|(k, v)| (k.into(), v.into())).collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::InlineElement> for InlineElement {
    fn from(val: kreuzberg::InlineElement) -> Self {
        Self {
            element_type: val.element_type.into(),
            content: val.content,
            attributes: val.attributes.as_ref().map(|v| format!("{v:?}")),
            metadata: val
                .metadata
                .map(|m| m.into_iter().map(|(k, v)| (k.into(), v.into())).collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DjotImage> for kreuzberg::DjotImage {
    fn from(val: DjotImage) -> Self {
        Self {
            src: val.src,
            alt: val.alt,
            title: val.title,
            attributes: Default::default(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DjotImage> for DjotImage {
    fn from(val: kreuzberg::DjotImage) -> Self {
        Self {
            src: val.src,
            alt: val.alt,
            title: val.title,
            attributes: val.attributes.as_ref().map(|v| format!("{v:?}")),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DjotLink> for kreuzberg::DjotLink {
    fn from(val: DjotLink) -> Self {
        Self {
            url: val.url,
            text: val.text,
            title: val.title,
            attributes: Default::default(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DjotLink> for DjotLink {
    fn from(val: kreuzberg::DjotLink) -> Self {
        Self {
            url: val.url,
            text: val.text,
            title: val.title,
            attributes: val.attributes.as_ref().map(|v| format!("{v:?}")),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<Footnote> for kreuzberg::Footnote {
    fn from(val: Footnote) -> Self {
        Self {
            label: val.label,
            content: val.content.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::Footnote> for Footnote {
    fn from(val: kreuzberg::Footnote) -> Self {
        Self {
            label: val.label,
            content: val.content.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DocumentStructure> for kreuzberg::DocumentStructure {
    fn from(val: DocumentStructure) -> Self {
        Self {
            nodes: val.nodes.into_iter().map(Into::into).collect(),
            source_format: val.source_format,
            relationships: val.relationships.into_iter().map(Into::into).collect(),
            node_types: val.node_types.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DocumentStructure> for DocumentStructure {
    fn from(val: kreuzberg::DocumentStructure) -> Self {
        Self {
            nodes: val.nodes.into_iter().map(Into::into).collect(),
            source_format: val.source_format,
            relationships: val.relationships.into_iter().map(Into::into).collect(),
            node_types: val.node_types.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DocumentRelationship> for kreuzberg::DocumentRelationship {
    fn from(val: DocumentRelationship) -> Self {
        Self {
            source: kreuzberg::NodeIndex(val.source),
            target: kreuzberg::NodeIndex(val.target),
            kind: val.kind.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DocumentRelationship> for DocumentRelationship {
    fn from(val: kreuzberg::DocumentRelationship) -> Self {
        Self {
            source: val.source.0,
            target: val.target.0,
            kind: val.kind.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DocumentNode> for kreuzberg::DocumentNode {
    fn from(val: DocumentNode) -> Self {
        Self {
            id: Default::default(),
            content: val.content.into(),
            parent: (val.parent).map(kreuzberg::NodeIndex),
            children: (val.children.into_iter().collect::<Vec<_>>())
                .into_iter()
                .map(kreuzberg::NodeIndex)
                .collect(),
            content_layer: val.content_layer.into(),
            page: val.page,
            page_end: val.page_end,
            bbox: val.bbox.map(Into::into),
            annotations: val.annotations.into_iter().map(Into::into).collect(),
            attributes: val
                .attributes
                .map(|m| m.into_iter().map(|(k, v)| (k.into(), v.into())).collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DocumentNode> for DocumentNode {
    fn from(val: kreuzberg::DocumentNode) -> Self {
        Self {
            id: format!("{:?}", val.id),
            content: val.content.into(),
            parent: val.parent.map(|v| v.0),
            children: val
                .children
                .iter()
                .map(|v| v.0)
                .collect::<Vec<_>>()
                .into_iter()
                .collect(),
            content_layer: val.content_layer.into(),
            page: val.page,
            page_end: val.page_end,
            bbox: val.bbox.map(Into::into),
            annotations: val.annotations.into_iter().map(Into::into).collect(),
            attributes: val
                .attributes
                .map(|m| m.into_iter().map(|(k, v)| (k.into(), v.into())).collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<TableGrid> for kreuzberg::TableGrid {
    fn from(val: TableGrid) -> Self {
        Self {
            rows: val.rows,
            cols: val.cols,
            cells: val.cells.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::TableGrid> for TableGrid {
    fn from(val: kreuzberg::TableGrid) -> Self {
        Self {
            rows: val.rows,
            cols: val.cols,
            cells: val.cells.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<GridCell> for kreuzberg::GridCell {
    fn from(val: GridCell) -> Self {
        Self {
            content: val.content,
            row: val.row,
            col: val.col,
            row_span: val.row_span,
            col_span: val.col_span,
            is_header: val.is_header,
            bbox: val.bbox.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::GridCell> for GridCell {
    fn from(val: kreuzberg::GridCell) -> Self {
        Self {
            content: val.content,
            row: val.row,
            col: val.col,
            row_span: val.row_span,
            col_span: val.col_span,
            is_header: val.is_header,
            bbox: val.bbox.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<TextAnnotation> for kreuzberg::TextAnnotation {
    fn from(val: TextAnnotation) -> Self {
        Self {
            start: val.start,
            end: val.end,
            kind: val.kind.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::TextAnnotation> for TextAnnotation {
    fn from(val: kreuzberg::TextAnnotation) -> Self {
        Self {
            start: val.start,
            end: val.end,
            kind: val.kind.into(),
        }
    }
}

#[allow(clippy::needless_update)]
#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ExtractionResult> for kreuzberg::ExtractionResult {
    fn from(val: ExtractionResult) -> Self {
        Self {
            content: val.content,
            mime_type: val.mime_type.into(),
            metadata: val.metadata.into(),
            extraction_method: val.extraction_method.map(Into::into),
            tables: val.tables.into_iter().map(Into::into).collect(),
            detected_languages: val.detected_languages.map(|v| v.into_iter().collect()),
            chunks: val.chunks.map(|v| v.into_iter().map(Into::into).collect()),
            images: val.images.map(|v| v.into_iter().map(Into::into).collect()),
            pages: val.pages.map(|v| v.into_iter().map(Into::into).collect()),
            elements: val.elements.map(|v| v.into_iter().map(Into::into).collect()),
            djot_content: val.djot_content.map(Into::into),
            ocr_elements: val.ocr_elements.map(|v| v.into_iter().map(Into::into).collect()),
            document: val.document.map(Into::into),
            extracted_keywords: val.extracted_keywords.map(|v| v.into_iter().map(Into::into).collect()),
            quality_score: val.quality_score,
            processing_warnings: val.processing_warnings.into_iter().map(Into::into).collect(),
            annotations: val.annotations.map(|v| v.into_iter().map(Into::into).collect()),
            children: val.children.map(|v| v.into_iter().map(Into::into).collect()),
            uris: val.uris.map(|v| v.into_iter().map(Into::into).collect()),
            revisions: val.revisions.map(|v| v.into_iter().map(Into::into).collect()),
            structured_output: val
                .structured_output
                .as_ref()
                .and_then(|s| serde_json::from_str(s).ok()),
            code_intelligence: val
                .code_intelligence
                .as_ref()
                .and_then(|s| serde_json::from_str(s).ok()),
            llm_usage: val.llm_usage.map(|v| v.into_iter().map(Into::into).collect()),
            formatted_content: val.formatted_content,
            ocr_internal_document: Default::default(),
            ..Default::default()
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ExtractionResult> for ExtractionResult {
    fn from(val: kreuzberg::ExtractionResult) -> Self {
        Self {
            content: val.content,
            mime_type: val.mime_type.to_string(),
            metadata: val.metadata.into(),
            extraction_method: val.extraction_method.map(Into::into),
            tables: val.tables.into_iter().map(Into::into).collect(),
            detected_languages: val.detected_languages.map(|v| v.into_iter().collect()),
            chunks: val.chunks.map(|v| v.into_iter().map(Into::into).collect()),
            images: val.images.map(|v| v.into_iter().map(Into::into).collect()),
            pages: val.pages.map(|v| v.into_iter().map(Into::into).collect()),
            elements: val.elements.map(|v| v.into_iter().map(Into::into).collect()),
            djot_content: val.djot_content.map(Into::into),
            ocr_elements: val.ocr_elements.map(|v| v.into_iter().map(Into::into).collect()),
            document: val.document.map(Into::into),
            extracted_keywords: val.extracted_keywords.map(|v| v.into_iter().map(Into::into).collect()),
            quality_score: val.quality_score,
            processing_warnings: val.processing_warnings.into_iter().map(Into::into).collect(),
            annotations: val.annotations.map(|v| v.into_iter().map(Into::into).collect()),
            children: val.children.map(|v| v.into_iter().map(Into::into).collect()),
            uris: val.uris.map(|v| v.into_iter().map(Into::into).collect()),
            revisions: val.revisions.map(|v| v.into_iter().map(Into::into).collect()),
            structured_output: val.structured_output.as_ref().map(ToString::to_string),
            code_intelligence: val.code_intelligence.as_ref().map(ToString::to_string),
            llm_usage: val.llm_usage.map(|v| v.into_iter().map(Into::into).collect()),
            formatted_content: val.formatted_content,
            ocr_internal_document: val.ocr_internal_document.as_ref().map(|v| format!("{v:?}")),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ArchiveEntry> for kreuzberg::ArchiveEntry {
    fn from(val: ArchiveEntry) -> Self {
        Self {
            path: val.path,
            mime_type: val.mime_type,
            result: Box::new(val.result.into()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ArchiveEntry> for ArchiveEntry {
    fn from(val: kreuzberg::ArchiveEntry) -> Self {
        Self {
            path: val.path,
            mime_type: val.mime_type,
            result: (*val.result).into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ProcessingWarning> for kreuzberg::ProcessingWarning {
    fn from(val: ProcessingWarning) -> Self {
        Self {
            source: val.source.into(),
            message: val.message.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ProcessingWarning> for ProcessingWarning {
    fn from(val: kreuzberg::ProcessingWarning) -> Self {
        Self {
            source: val.source.to_string(),
            message: val.message.to_string(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<LlmUsage> for kreuzberg::LlmUsage {
    fn from(val: LlmUsage) -> Self {
        Self {
            model: val.model,
            source: val.source,
            input_tokens: val.input_tokens,
            output_tokens: val.output_tokens,
            total_tokens: val.total_tokens,
            estimated_cost: val.estimated_cost,
            finish_reason: val.finish_reason,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::LlmUsage> for LlmUsage {
    fn from(val: kreuzberg::LlmUsage) -> Self {
        Self {
            model: val.model,
            source: val.source,
            input_tokens: val.input_tokens,
            output_tokens: val.output_tokens,
            total_tokens: val.total_tokens,
            estimated_cost: val.estimated_cost,
            finish_reason: val.finish_reason,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<Chunk> for kreuzberg::Chunk {
    fn from(val: Chunk) -> Self {
        Self {
            content: val.content,
            chunk_type: val.chunk_type.into(),
            embedding: val.embedding.map(|v| v.into_iter().collect()),
            metadata: val.metadata.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::Chunk> for Chunk {
    fn from(val: kreuzberg::Chunk) -> Self {
        Self {
            content: val.content,
            chunk_type: val.chunk_type.into(),
            embedding: val.embedding.map(|v| v.into_iter().collect()),
            metadata: val.metadata.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<HeadingContext> for kreuzberg::HeadingContext {
    fn from(val: HeadingContext) -> Self {
        Self {
            headings: val.headings.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::HeadingContext> for HeadingContext {
    fn from(val: kreuzberg::HeadingContext) -> Self {
        Self {
            headings: val.headings.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<HeadingLevel> for kreuzberg::HeadingLevel {
    fn from(val: HeadingLevel) -> Self {
        Self {
            level: val.level,
            text: val.text,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::HeadingLevel> for HeadingLevel {
    fn from(val: kreuzberg::HeadingLevel) -> Self {
        Self {
            level: val.level,
            text: val.text,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ChunkMetadata> for kreuzberg::ChunkMetadata {
    fn from(val: ChunkMetadata) -> Self {
        Self {
            byte_start: val.byte_start,
            byte_end: val.byte_end,
            token_count: val.token_count,
            chunk_index: val.chunk_index,
            total_chunks: val.total_chunks,
            first_page: val.first_page,
            last_page: val.last_page,
            heading_context: val.heading_context.map(Into::into),
            image_indices: val.image_indices.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ChunkMetadata> for ChunkMetadata {
    fn from(val: kreuzberg::ChunkMetadata) -> Self {
        Self {
            byte_start: val.byte_start,
            byte_end: val.byte_end,
            token_count: val.token_count,
            chunk_index: val.chunk_index,
            total_chunks: val.total_chunks,
            first_page: val.first_page,
            last_page: val.last_page,
            heading_context: val.heading_context.map(Into::into),
            image_indices: val.image_indices.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ExtractedImage> for kreuzberg::ExtractedImage {
    fn from(val: ExtractedImage) -> Self {
        Self {
            data: val.data.to_vec().into(),
            format: val.format.into(),
            image_index: val.image_index,
            page_number: val.page_number,
            width: val.width,
            height: val.height,
            colorspace: val.colorspace,
            bits_per_component: val.bits_per_component,
            is_mask: val.is_mask,
            description: val.description,
            ocr_result: val.ocr_result.map(Into::into).map(Box::new),
            bounding_box: val.bounding_box.map(Into::into),
            source_path: val.source_path,
            image_kind: val.image_kind.map(Into::into),
            kind_confidence: val.kind_confidence,
            cluster_id: val.cluster_id,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ExtractedImage> for ExtractedImage {
    fn from(val: kreuzberg::ExtractedImage) -> Self {
        Self {
            data: val.data.to_vec().into(),
            format: val.format.to_string(),
            image_index: val.image_index,
            page_number: val.page_number,
            width: val.width,
            height: val.height,
            colorspace: val.colorspace,
            bits_per_component: val.bits_per_component,
            is_mask: val.is_mask,
            description: val.description,
            ocr_result: val.ocr_result.map(|v| (*v).into()),
            bounding_box: val.bounding_box.map(Into::into),
            source_path: val.source_path,
            image_kind: val.image_kind.map(Into::into),
            kind_confidence: val.kind_confidence,
            cluster_id: val.cluster_id,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<BoundingBox> for kreuzberg::BoundingBox {
    fn from(val: BoundingBox) -> Self {
        Self {
            x0: val.x0,
            y0: val.y0,
            x1: val.x1,
            y1: val.y1,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::BoundingBox> for BoundingBox {
    fn from(val: kreuzberg::BoundingBox) -> Self {
        Self {
            x0: val.x0,
            y0: val.y0,
            x1: val.x1,
            y1: val.y1,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ElementMetadata> for kreuzberg::ElementMetadata {
    fn from(val: ElementMetadata) -> Self {
        Self {
            page_number: val.page_number,
            filename: val.filename,
            coordinates: val.coordinates.map(Into::into),
            element_index: val.element_index,
            additional: val.additional.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ElementMetadata> for ElementMetadata {
    fn from(val: kreuzberg::ElementMetadata) -> Self {
        Self {
            page_number: val.page_number,
            filename: val.filename,
            coordinates: val.coordinates.map(Into::into),
            element_index: val.element_index,
            additional: val.additional.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<Element> for kreuzberg::Element {
    fn from(val: Element) -> Self {
        Self {
            element_id: Default::default(),
            element_type: val.element_type.into(),
            text: val.text,
            metadata: val.metadata.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::Element> for Element {
    fn from(val: kreuzberg::Element) -> Self {
        Self {
            element_id: format!("{:?}", val.element_id),
            element_type: val.element_type.into(),
            text: val.text,
            metadata: val.metadata.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ExcelWorkbook> for ExcelWorkbook {
    fn from(val: kreuzberg::ExcelWorkbook) -> Self {
        Self {
            sheets: val.sheets.into_iter().map(Into::into).collect(),
            metadata: val.metadata.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            revisions: val.revisions.map(|v| v.into_iter().map(Into::into).collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ExcelSheet> for ExcelSheet {
    fn from(val: kreuzberg::ExcelSheet) -> Self {
        Self {
            name: val.name,
            markdown: val.markdown,
            row_count: val.row_count,
            col_count: val.col_count,
            cell_count: val.cell_count,
            table_cells: val.table_cells.map(|v| v.into_iter().collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::XmlExtractionResult> for XmlExtractionResult {
    fn from(val: kreuzberg::XmlExtractionResult) -> Self {
        Self {
            content: val.content,
            element_count: val.element_count,
            unique_elements: val.unique_elements.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::TextExtractionResult> for TextExtractionResult {
    fn from(val: kreuzberg::TextExtractionResult) -> Self {
        Self {
            content: val.content,
            line_count: val.line_count,
            word_count: val.word_count,
            character_count: val.character_count,
            headers: val.headers.map(|v| v.into_iter().collect()),
            links: val.links.as_ref().map(|v| {
                v.iter()
                    .map(|(a, b)| vec![a.to_string(), b.to_string()])
                    .collect::<Vec<Vec<String>>>()
            }),
            code_blocks: val.code_blocks.as_ref().map(|v| {
                v.iter()
                    .map(|(a, b)| vec![a.to_string(), b.to_string()])
                    .collect::<Vec<Vec<String>>>()
            }),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PptxExtractionResult> for PptxExtractionResult {
    fn from(val: kreuzberg::PptxExtractionResult) -> Self {
        Self {
            content: val.content,
            metadata: val.metadata.into(),
            slide_count: val.slide_count,
            image_count: val.image_count,
            table_count: val.table_count,
            images: val.images.into_iter().map(Into::into).collect(),
            page_structure: val.page_structure.map(Into::into),
            page_contents: val.page_contents.map(|v| v.into_iter().map(Into::into).collect()),
            document: val.document.map(Into::into),
            hyperlinks: val.hyperlinks.iter().map(|i| format!("{:?}", i)).collect(),
            office_metadata: val
                .office_metadata
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
            revisions: val.revisions.map(|v| v.into_iter().map(Into::into).collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::EmailExtractionResult> for EmailExtractionResult {
    fn from(val: kreuzberg::EmailExtractionResult) -> Self {
        Self {
            subject: val.subject,
            from_email: val.from_email,
            to_emails: val.to_emails.into_iter().collect(),
            cc_emails: val.cc_emails.into_iter().collect(),
            bcc_emails: val.bcc_emails.into_iter().collect(),
            date: val.date,
            message_id: val.message_id,
            plain_text: val.plain_text,
            html_content: val.html_content,
            content: val.content,
            attachments: val.attachments.into_iter().map(Into::into).collect(),
            metadata: val.metadata.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::EmailAttachment> for EmailAttachment {
    fn from(val: kreuzberg::EmailAttachment) -> Self {
        Self {
            name: val.name,
            filename: val.filename,
            mime_type: val.mime_type,
            size: val.size,
            is_image: val.is_image,
            data: val.data.map(|v| v.to_vec().into()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrExtractionResult> for kreuzberg::OcrExtractionResult {
    fn from(val: OcrExtractionResult) -> Self {
        Self {
            content: val.content,
            mime_type: val.mime_type,
            metadata: val
                .metadata
                .into_iter()
                .map(|(k, v)| (k.into(), serde_json::from_str(&v).unwrap_or_default()))
                .collect(),
            tables: val.tables.into_iter().map(Into::into).collect(),
            ocr_elements: val.ocr_elements.map(|v| v.into_iter().map(Into::into).collect()),
            internal_document: Default::default(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrExtractionResult> for OcrExtractionResult {
    fn from(val: kreuzberg::OcrExtractionResult) -> Self {
        Self {
            content: val.content,
            mime_type: val.mime_type,
            metadata: val
                .metadata
                .into_iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            tables: val.tables.into_iter().map(Into::into).collect(),
            ocr_elements: val.ocr_elements.map(|v| v.into_iter().map(Into::into).collect()),
            internal_document: val.internal_document.as_ref().map(|v| format!("{v:?}")),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrTable> for kreuzberg::OcrTable {
    fn from(val: OcrTable) -> Self {
        Self {
            cells: val.cells.into_iter().collect(),
            markdown: val.markdown,
            page_number: val.page_number,
            bounding_box: val.bounding_box.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrTable> for OcrTable {
    fn from(val: kreuzberg::OcrTable) -> Self {
        Self {
            cells: val.cells.into_iter().collect(),
            markdown: val.markdown,
            page_number: val.page_number,
            bounding_box: val.bounding_box.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrTableBoundingBox> for kreuzberg::OcrTableBoundingBox {
    fn from(val: OcrTableBoundingBox) -> Self {
        Self {
            left: val.left,
            top: val.top,
            right: val.right,
            bottom: val.bottom,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrTableBoundingBox> for OcrTableBoundingBox {
    fn from(val: kreuzberg::OcrTableBoundingBox) -> Self {
        Self {
            left: val.left,
            top: val.top,
            right: val.right,
            bottom: val.bottom,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ImagePreprocessingConfig> for kreuzberg::ImagePreprocessingConfig {
    fn from(val: ImagePreprocessingConfig) -> Self {
        Self {
            target_dpi: val.target_dpi,
            auto_rotate: val.auto_rotate,
            deskew: val.deskew,
            denoise: val.denoise,
            contrast_enhance: val.contrast_enhance,
            binarization_method: val.binarization_method,
            invert_colors: val.invert_colors,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ImagePreprocessingConfig> for ImagePreprocessingConfig {
    fn from(val: kreuzberg::ImagePreprocessingConfig) -> Self {
        Self {
            target_dpi: val.target_dpi,
            auto_rotate: val.auto_rotate,
            deskew: val.deskew,
            denoise: val.denoise,
            contrast_enhance: val.contrast_enhance,
            binarization_method: val.binarization_method,
            invert_colors: val.invert_colors,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<TesseractConfig> for kreuzberg::TesseractConfig {
    fn from(val: TesseractConfig) -> Self {
        Self {
            language: val.language,
            psm: val.psm,
            output_format: val.output_format,
            oem: val.oem,
            min_confidence: val.min_confidence,
            preprocessing: val.preprocessing.map(Into::into),
            enable_table_detection: val.enable_table_detection,
            table_min_confidence: val.table_min_confidence,
            table_column_threshold: val.table_column_threshold,
            table_row_threshold_ratio: val.table_row_threshold_ratio,
            use_cache: val.use_cache,
            classify_use_pre_adapted_templates: val.classify_use_pre_adapted_templates,
            language_model_ngram_on: val.language_model_ngram_on,
            tessedit_dont_blkrej_good_wds: val.tessedit_dont_blkrej_good_wds,
            tessedit_dont_rowrej_good_wds: val.tessedit_dont_rowrej_good_wds,
            tessedit_enable_dict_correction: val.tessedit_enable_dict_correction,
            tessedit_char_whitelist: val.tessedit_char_whitelist,
            tessedit_char_blacklist: val.tessedit_char_blacklist,
            tessedit_use_primary_params_model: val.tessedit_use_primary_params_model,
            textord_space_size_is_variable: val.textord_space_size_is_variable,
            thresholding_method: val.thresholding_method,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::TesseractConfig> for TesseractConfig {
    fn from(val: kreuzberg::TesseractConfig) -> Self {
        Self {
            language: val.language,
            psm: val.psm,
            output_format: val.output_format,
            oem: val.oem,
            min_confidence: val.min_confidence,
            preprocessing: val.preprocessing.map(Into::into),
            enable_table_detection: val.enable_table_detection,
            table_min_confidence: val.table_min_confidence,
            table_column_threshold: val.table_column_threshold,
            table_row_threshold_ratio: val.table_row_threshold_ratio,
            use_cache: val.use_cache,
            classify_use_pre_adapted_templates: val.classify_use_pre_adapted_templates,
            language_model_ngram_on: val.language_model_ngram_on,
            tessedit_dont_blkrej_good_wds: val.tessedit_dont_blkrej_good_wds,
            tessedit_dont_rowrej_good_wds: val.tessedit_dont_rowrej_good_wds,
            tessedit_enable_dict_correction: val.tessedit_enable_dict_correction,
            tessedit_char_whitelist: val.tessedit_char_whitelist,
            tessedit_char_blacklist: val.tessedit_char_blacklist,
            tessedit_use_primary_params_model: val.tessedit_use_primary_params_model,
            textord_space_size_is_variable: val.textord_space_size_is_variable,
            thresholding_method: val.thresholding_method,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ImagePreprocessingMetadata> for kreuzberg::ImagePreprocessingMetadata {
    fn from(val: ImagePreprocessingMetadata) -> Self {
        Self {
            original_dimensions: Default::default(),
            original_dpi: Default::default(),
            target_dpi: val.target_dpi,
            scale_factor: val.scale_factor,
            auto_adjusted: val.auto_adjusted,
            final_dpi: val.final_dpi,
            new_dimensions: Default::default(),
            resample_method: val.resample_method,
            dimension_clamped: val.dimension_clamped,
            calculated_dpi: val.calculated_dpi,
            skipped_resize: val.skipped_resize,
            resize_error: val.resize_error,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ImagePreprocessingMetadata> for ImagePreprocessingMetadata {
    fn from(val: kreuzberg::ImagePreprocessingMetadata) -> Self {
        Self {
            original_dimensions: vec![val.original_dimensions.0 as _, val.original_dimensions.1 as _],
            original_dpi: vec![val.original_dpi.0 as _, val.original_dpi.1 as _],
            target_dpi: val.target_dpi,
            scale_factor: val.scale_factor,
            auto_adjusted: val.auto_adjusted,
            final_dpi: val.final_dpi,
            new_dimensions: val.new_dimensions.map(|t| {
                let arr: Vec<_> = [t.0, t.1].into_iter().map(|v| v as _).collect();
                arr
            }),
            resample_method: val.resample_method,
            dimension_clamped: val.dimension_clamped,
            calculated_dpi: val.calculated_dpi,
            skipped_resize: val.skipped_resize,
            resize_error: val.resize_error,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<Metadata> for kreuzberg::Metadata {
    fn from(val: Metadata) -> Self {
        Self {
            title: val.title,
            subject: val.subject,
            authors: val.authors.map(|v| v.into_iter().collect()),
            keywords: val.keywords.map(|v| v.into_iter().collect()),
            language: val.language,
            created_at: val.created_at,
            modified_at: val.modified_at,
            created_by: val.created_by,
            modified_by: val.modified_by,
            pages: val.pages.map(Into::into),
            format: val.format.map(Into::into),
            image_preprocessing: val.image_preprocessing.map(Into::into),
            json_schema: val.json_schema.as_ref().and_then(|s| serde_json::from_str(s).ok()),
            error: val.error.map(Into::into),
            extraction_duration_ms: val.extraction_duration_ms,
            category: val.category,
            tags: val.tags.map(|v| v.into_iter().collect()),
            document_version: val.document_version,
            abstract_text: val.abstract_text,
            output_format: val.output_format,
            ocr_used: val.ocr_used,
            additional: val
                .additional
                .into_iter()
                .map(|(k, v)| (k.into(), serde_json::from_str(&v).unwrap_or_default()))
                .collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::Metadata> for Metadata {
    fn from(val: kreuzberg::Metadata) -> Self {
        Self {
            title: val.title,
            subject: val.subject,
            authors: val.authors.map(|v| v.into_iter().collect()),
            keywords: val.keywords.map(|v| v.into_iter().collect()),
            language: val.language,
            created_at: val.created_at,
            modified_at: val.modified_at,
            created_by: val.created_by,
            modified_by: val.modified_by,
            pages: val.pages.map(Into::into),
            format: val.format.map(Into::into),
            image_preprocessing: val.image_preprocessing.map(Into::into),
            json_schema: val.json_schema.as_ref().map(ToString::to_string),
            error: val.error.map(Into::into),
            extraction_duration_ms: val.extraction_duration_ms,
            category: val.category,
            tags: val.tags.map(|v| v.into_iter().collect()),
            document_version: val.document_version,
            abstract_text: val.abstract_text,
            output_format: val.output_format,
            ocr_used: val.ocr_used,
            additional: val
                .additional
                .into_iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ExcelMetadata> for kreuzberg::ExcelMetadata {
    fn from(val: ExcelMetadata) -> Self {
        Self {
            sheet_count: val.sheet_count,
            sheet_names: val.sheet_names.map(|v| v.into_iter().collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ExcelMetadata> for ExcelMetadata {
    fn from(val: kreuzberg::ExcelMetadata) -> Self {
        Self {
            sheet_count: val.sheet_count,
            sheet_names: val.sheet_names.map(|v| v.into_iter().collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<EmailMetadata> for kreuzberg::EmailMetadata {
    fn from(val: EmailMetadata) -> Self {
        Self {
            from_email: val.from_email,
            from_name: val.from_name,
            to_emails: val.to_emails.into_iter().collect(),
            cc_emails: val.cc_emails.into_iter().collect(),
            bcc_emails: val.bcc_emails.into_iter().collect(),
            message_id: val.message_id,
            attachments: val.attachments.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::EmailMetadata> for EmailMetadata {
    fn from(val: kreuzberg::EmailMetadata) -> Self {
        Self {
            from_email: val.from_email,
            from_name: val.from_name,
            to_emails: val.to_emails.into_iter().collect(),
            cc_emails: val.cc_emails.into_iter().collect(),
            bcc_emails: val.bcc_emails.into_iter().collect(),
            message_id: val.message_id,
            attachments: val.attachments.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ArchiveMetadata> for kreuzberg::ArchiveMetadata {
    fn from(val: ArchiveMetadata) -> Self {
        Self {
            format: val.format.into(),
            file_count: val.file_count,
            file_list: val.file_list.into_iter().collect(),
            total_size: val.total_size,
            compressed_size: val.compressed_size,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ArchiveMetadata> for ArchiveMetadata {
    fn from(val: kreuzberg::ArchiveMetadata) -> Self {
        Self {
            format: val.format.to_string(),
            file_count: val.file_count,
            file_list: val.file_list.into_iter().collect(),
            total_size: val.total_size,
            compressed_size: val.compressed_size,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ImageMetadata> for kreuzberg::ImageMetadata {
    fn from(val: ImageMetadata) -> Self {
        Self {
            width: val.width,
            height: val.height,
            format: val.format,
            exif: val.exif.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ImageMetadata> for ImageMetadata {
    fn from(val: kreuzberg::ImageMetadata) -> Self {
        Self {
            width: val.width,
            height: val.height,
            format: val.format,
            exif: val.exif.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<XmlMetadata> for kreuzberg::XmlMetadata {
    fn from(val: XmlMetadata) -> Self {
        Self {
            element_count: val.element_count,
            unique_elements: val.unique_elements.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::XmlMetadata> for XmlMetadata {
    fn from(val: kreuzberg::XmlMetadata) -> Self {
        Self {
            element_count: val.element_count,
            unique_elements: val.unique_elements.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<TextMetadata> for kreuzberg::TextMetadata {
    fn from(val: TextMetadata) -> Self {
        Self {
            line_count: val.line_count,
            word_count: val.word_count,
            character_count: val.character_count,
            headers: val.headers.map(|v| v.into_iter().collect()),
            links: Default::default(),
            code_blocks: Default::default(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::TextMetadata> for TextMetadata {
    fn from(val: kreuzberg::TextMetadata) -> Self {
        Self {
            line_count: val.line_count,
            word_count: val.word_count,
            character_count: val.character_count,
            headers: val.headers.map(|v| v.into_iter().collect()),
            links: val.links.as_ref().map(|v| {
                v.iter()
                    .map(|(a, b)| vec![a.to_string(), b.to_string()])
                    .collect::<Vec<Vec<String>>>()
            }),
            code_blocks: val.code_blocks.as_ref().map(|v| {
                v.iter()
                    .map(|(a, b)| vec![a.to_string(), b.to_string()])
                    .collect::<Vec<Vec<String>>>()
            }),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<HeaderMetadata> for kreuzberg::HeaderMetadata {
    fn from(val: HeaderMetadata) -> Self {
        Self {
            level: val.level,
            text: val.text,
            id: val.id,
            depth: val.depth,
            html_offset: val.html_offset,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::HeaderMetadata> for HeaderMetadata {
    fn from(val: kreuzberg::HeaderMetadata) -> Self {
        Self {
            level: val.level,
            text: val.text,
            id: val.id,
            depth: val.depth,
            html_offset: val.html_offset,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<LinkMetadata> for kreuzberg::LinkMetadata {
    fn from(val: LinkMetadata) -> Self {
        Self {
            href: val.href,
            text: val.text,
            title: val.title,
            link_type: val.link_type.into(),
            rel: val.rel.into_iter().collect(),
            attributes: Default::default(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::LinkMetadata> for LinkMetadata {
    fn from(val: kreuzberg::LinkMetadata) -> Self {
        Self {
            href: val.href,
            text: val.text,
            title: val.title,
            link_type: val.link_type.into(),
            rel: val.rel.into_iter().collect(),
            attributes: val
                .attributes
                .iter()
                .map(|(a, b)| vec![a.to_string(), b.to_string()])
                .collect::<Vec<Vec<String>>>(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ImageMetadataType> for kreuzberg::ImageMetadataType {
    fn from(val: ImageMetadataType) -> Self {
        Self {
            src: val.src,
            alt: val.alt,
            title: val.title,
            dimensions: Default::default(),
            image_type: val.image_type.into(),
            attributes: Default::default(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ImageMetadataType> for ImageMetadataType {
    fn from(val: kreuzberg::ImageMetadataType) -> Self {
        Self {
            src: val.src,
            alt: val.alt,
            title: val.title,
            dimensions: val.dimensions.map(|t| {
                let arr: Vec<_> = [t.0, t.1].into_iter().map(|v| v as _).collect();
                arr
            }),
            image_type: val.image_type.into(),
            attributes: val
                .attributes
                .iter()
                .map(|(a, b)| vec![a.to_string(), b.to_string()])
                .collect::<Vec<Vec<String>>>(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<StructuredData> for kreuzberg::StructuredData {
    fn from(val: StructuredData) -> Self {
        Self {
            data_type: val.data_type.into(),
            raw_json: val.raw_json,
            schema_type: val.schema_type,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::StructuredData> for StructuredData {
    fn from(val: kreuzberg::StructuredData) -> Self {
        Self {
            data_type: val.data_type.into(),
            raw_json: val.raw_json,
            schema_type: val.schema_type,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<HtmlMetadata> for kreuzberg::HtmlMetadata {
    fn from(val: HtmlMetadata) -> Self {
        Self {
            title: val.title,
            description: val.description,
            keywords: val.keywords.into_iter().collect(),
            author: val.author,
            canonical_url: val.canonical_url,
            base_href: val.base_href,
            language: val.language,
            text_direction: val.text_direction.map(Into::into),
            open_graph: val.open_graph.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            twitter_card: val
                .twitter_card
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
            meta_tags: val.meta_tags.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            headers: val.headers.into_iter().map(Into::into).collect(),
            links: val.links.into_iter().map(Into::into).collect(),
            images: val.images.into_iter().map(Into::into).collect(),
            structured_data: val.structured_data.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::HtmlMetadata> for HtmlMetadata {
    fn from(val: kreuzberg::HtmlMetadata) -> Self {
        Self {
            title: val.title,
            description: val.description,
            keywords: val.keywords.into_iter().collect(),
            author: val.author,
            canonical_url: val.canonical_url,
            base_href: val.base_href,
            language: val.language,
            text_direction: val.text_direction.map(Into::into),
            open_graph: val.open_graph.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            twitter_card: val
                .twitter_card
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
            meta_tags: val.meta_tags.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            headers: val.headers.into_iter().map(Into::into).collect(),
            links: val.links.into_iter().map(Into::into).collect(),
            images: val.images.into_iter().map(Into::into).collect(),
            structured_data: val.structured_data.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrMetadata> for kreuzberg::OcrMetadata {
    fn from(val: OcrMetadata) -> Self {
        Self {
            language: val.language,
            psm: val.psm,
            output_format: val.output_format,
            table_count: val.table_count,
            table_rows: val.table_rows,
            table_cols: val.table_cols,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrMetadata> for OcrMetadata {
    fn from(val: kreuzberg::OcrMetadata) -> Self {
        Self {
            language: val.language,
            psm: val.psm,
            output_format: val.output_format,
            table_count: val.table_count,
            table_rows: val.table_rows,
            table_cols: val.table_cols,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ErrorMetadata> for kreuzberg::ErrorMetadata {
    fn from(val: ErrorMetadata) -> Self {
        Self {
            error_type: val.error_type,
            message: val.message,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ErrorMetadata> for ErrorMetadata {
    fn from(val: kreuzberg::ErrorMetadata) -> Self {
        Self {
            error_type: val.error_type,
            message: val.message,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PptxMetadata> for kreuzberg::PptxMetadata {
    fn from(val: PptxMetadata) -> Self {
        Self {
            slide_count: val.slide_count,
            slide_names: val.slide_names.into_iter().collect(),
            image_count: val.image_count,
            table_count: val.table_count,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PptxMetadata> for PptxMetadata {
    fn from(val: kreuzberg::PptxMetadata) -> Self {
        Self {
            slide_count: val.slide_count,
            slide_names: val.slide_names.into_iter().collect(),
            image_count: val.image_count,
            table_count: val.table_count,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DocxMetadata> for kreuzberg::DocxMetadata {
    fn from(val: DocxMetadata) -> Self {
        Self {
            core_properties: val.core_properties.map(Into::into),
            app_properties: val.app_properties.map(Into::into),
            custom_properties: val.custom_properties.map(|m| {
                m.into_iter()
                    .map(|(k, v)| (k.into(), serde_json::from_str(&v).unwrap_or_default()))
                    .collect()
            }),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DocxMetadata> for DocxMetadata {
    fn from(val: kreuzberg::DocxMetadata) -> Self {
        Self {
            core_properties: val.core_properties.map(Into::into),
            app_properties: val.app_properties.map(Into::into),
            custom_properties: val
                .custom_properties
                .map(|m| m.into_iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<CsvMetadata> for kreuzberg::CsvMetadata {
    fn from(val: CsvMetadata) -> Self {
        Self {
            row_count: val.row_count,
            column_count: val.column_count,
            delimiter: val.delimiter,
            has_header: val.has_header,
            column_types: val.column_types.map(|v| v.into_iter().collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::CsvMetadata> for CsvMetadata {
    fn from(val: kreuzberg::CsvMetadata) -> Self {
        Self {
            row_count: val.row_count,
            column_count: val.column_count,
            delimiter: val.delimiter,
            has_header: val.has_header,
            column_types: val.column_types.map(|v| v.into_iter().collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<BibtexMetadata> for kreuzberg::BibtexMetadata {
    fn from(val: BibtexMetadata) -> Self {
        Self {
            entry_count: val.entry_count,
            citation_keys: val.citation_keys.into_iter().collect(),
            authors: val.authors.into_iter().collect(),
            year_range: val.year_range.map(Into::into),
            entry_types: val.entry_types.map(|m| m.into_iter().collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::BibtexMetadata> for BibtexMetadata {
    fn from(val: kreuzberg::BibtexMetadata) -> Self {
        Self {
            entry_count: val.entry_count,
            citation_keys: val.citation_keys.into_iter().collect(),
            authors: val.authors.into_iter().collect(),
            year_range: val.year_range.map(Into::into),
            entry_types: val.entry_types.map(|m| m.into_iter().collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<CitationMetadata> for kreuzberg::CitationMetadata {
    fn from(val: CitationMetadata) -> Self {
        Self {
            citation_count: val.citation_count,
            format: val.format,
            authors: val.authors.into_iter().collect(),
            year_range: val.year_range.map(Into::into),
            dois: val.dois.into_iter().collect(),
            keywords: val.keywords.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::CitationMetadata> for CitationMetadata {
    fn from(val: kreuzberg::CitationMetadata) -> Self {
        Self {
            citation_count: val.citation_count,
            format: val.format,
            authors: val.authors.into_iter().collect(),
            year_range: val.year_range.map(Into::into),
            dois: val.dois.into_iter().collect(),
            keywords: val.keywords.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<YearRange> for kreuzberg::YearRange {
    fn from(val: YearRange) -> Self {
        Self {
            min: val.min,
            max: val.max,
            years: val.years.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::YearRange> for YearRange {
    fn from(val: kreuzberg::YearRange) -> Self {
        Self {
            min: val.min,
            max: val.max,
            years: val.years.into_iter().collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<FictionBookMetadata> for kreuzberg::FictionBookMetadata {
    fn from(val: FictionBookMetadata) -> Self {
        Self {
            genres: val.genres.into_iter().collect(),
            sequences: val.sequences.into_iter().collect(),
            annotation: val.annotation,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::FictionBookMetadata> for FictionBookMetadata {
    fn from(val: kreuzberg::FictionBookMetadata) -> Self {
        Self {
            genres: val.genres.into_iter().collect(),
            sequences: val.sequences.into_iter().collect(),
            annotation: val.annotation,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DbfMetadata> for kreuzberg::DbfMetadata {
    fn from(val: DbfMetadata) -> Self {
        Self {
            record_count: val.record_count,
            field_count: val.field_count,
            fields: val.fields.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DbfMetadata> for DbfMetadata {
    fn from(val: kreuzberg::DbfMetadata) -> Self {
        Self {
            record_count: val.record_count,
            field_count: val.field_count,
            fields: val.fields.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DbfFieldInfo> for kreuzberg::DbfFieldInfo {
    fn from(val: DbfFieldInfo) -> Self {
        Self {
            name: val.name,
            field_type: val.field_type,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DbfFieldInfo> for DbfFieldInfo {
    fn from(val: kreuzberg::DbfFieldInfo) -> Self {
        Self {
            name: val.name,
            field_type: val.field_type,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<JatsMetadata> for kreuzberg::JatsMetadata {
    fn from(val: JatsMetadata) -> Self {
        Self {
            copyright: val.copyright,
            license: val.license,
            history_dates: val
                .history_dates
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
            contributor_roles: val.contributor_roles.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::JatsMetadata> for JatsMetadata {
    fn from(val: kreuzberg::JatsMetadata) -> Self {
        Self {
            copyright: val.copyright,
            license: val.license,
            history_dates: val
                .history_dates
                .into_iter()
                .map(|(k, v)| (k.into(), v.into()))
                .collect(),
            contributor_roles: val.contributor_roles.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ContributorRole> for kreuzberg::ContributorRole {
    fn from(val: ContributorRole) -> Self {
        Self {
            name: val.name,
            role: val.role,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ContributorRole> for ContributorRole {
    fn from(val: kreuzberg::ContributorRole) -> Self {
        Self {
            name: val.name,
            role: val.role,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<EpubMetadata> for kreuzberg::EpubMetadata {
    fn from(val: EpubMetadata) -> Self {
        Self {
            coverage: val.coverage,
            dc_format: val.dc_format,
            relation: val.relation,
            source: val.source,
            dc_type: val.dc_type,
            cover_image: val.cover_image,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::EpubMetadata> for EpubMetadata {
    fn from(val: kreuzberg::EpubMetadata) -> Self {
        Self {
            coverage: val.coverage,
            dc_format: val.dc_format,
            relation: val.relation,
            source: val.source,
            dc_type: val.dc_type,
            cover_image: val.cover_image,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PstMetadata> for kreuzberg::PstMetadata {
    fn from(val: PstMetadata) -> Self {
        Self {
            message_count: val.message_count,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PstMetadata> for PstMetadata {
    fn from(val: kreuzberg::PstMetadata) -> Self {
        Self {
            message_count: val.message_count,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrConfidence> for kreuzberg::OcrConfidence {
    fn from(val: OcrConfidence) -> Self {
        Self {
            detection: val.detection,
            recognition: val.recognition,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrConfidence> for OcrConfidence {
    fn from(val: kreuzberg::OcrConfidence) -> Self {
        Self {
            detection: val.detection,
            recognition: val.recognition,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrRotation> for kreuzberg::OcrRotation {
    fn from(val: OcrRotation) -> Self {
        Self {
            angle_degrees: val.angle_degrees,
            confidence: val.confidence,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrRotation> for OcrRotation {
    fn from(val: kreuzberg::OcrRotation) -> Self {
        Self {
            angle_degrees: val.angle_degrees,
            confidence: val.confidence,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrElement> for kreuzberg::OcrElement {
    fn from(val: OcrElement) -> Self {
        Self {
            text: val.text,
            geometry: val.geometry.into(),
            confidence: val.confidence.into(),
            level: val.level.into(),
            rotation: val.rotation.map(Into::into),
            page_number: val.page_number,
            parent_id: val.parent_id,
            backend_metadata: val
                .backend_metadata
                .into_iter()
                .map(|(k, v)| (k.into(), serde_json::from_str(&v).unwrap_or_default()))
                .collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrElement> for OcrElement {
    fn from(val: kreuzberg::OcrElement) -> Self {
        Self {
            text: val.text,
            geometry: val.geometry.into(),
            confidence: val.confidence.into(),
            level: val.level.into(),
            rotation: val.rotation.map(Into::into),
            page_number: val.page_number,
            parent_id: val.parent_id,
            backend_metadata: val
                .backend_metadata
                .into_iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<OcrElementConfig> for kreuzberg::OcrElementConfig {
    fn from(val: OcrElementConfig) -> Self {
        Self {
            include_elements: val.include_elements,
            min_level: val.min_level.into(),
            min_confidence: val.min_confidence,
            build_hierarchy: val.build_hierarchy,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OcrElementConfig> for OcrElementConfig {
    fn from(val: kreuzberg::OcrElementConfig) -> Self {
        Self {
            include_elements: val.include_elements,
            min_level: val.min_level.into(),
            min_confidence: val.min_confidence,
            build_hierarchy: val.build_hierarchy,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PageStructure> for kreuzberg::PageStructure {
    fn from(val: PageStructure) -> Self {
        Self {
            total_count: val.total_count,
            unit_type: val.unit_type.into(),
            boundaries: val.boundaries.map(|v| v.into_iter().map(Into::into).collect()),
            pages: val.pages.map(|v| v.into_iter().map(Into::into).collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PageStructure> for PageStructure {
    fn from(val: kreuzberg::PageStructure) -> Self {
        Self {
            total_count: val.total_count,
            unit_type: val.unit_type.into(),
            boundaries: val.boundaries.map(|v| v.into_iter().map(Into::into).collect()),
            pages: val.pages.map(|v| v.into_iter().map(Into::into).collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PageBoundary> for kreuzberg::PageBoundary {
    fn from(val: PageBoundary) -> Self {
        Self {
            byte_start: val.byte_start,
            byte_end: val.byte_end,
            page_number: val.page_number,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PageBoundary> for PageBoundary {
    fn from(val: kreuzberg::PageBoundary) -> Self {
        Self {
            byte_start: val.byte_start,
            byte_end: val.byte_end,
            page_number: val.page_number,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PageInfo> for kreuzberg::PageInfo {
    fn from(val: PageInfo) -> Self {
        Self {
            number: val.number,
            title: val.title,
            dimensions: Default::default(),
            image_count: val.image_count,
            table_count: val.table_count,
            hidden: val.hidden,
            is_blank: val.is_blank,
            has_vector_graphics: val.has_vector_graphics,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PageInfo> for PageInfo {
    fn from(val: kreuzberg::PageInfo) -> Self {
        Self {
            number: val.number,
            title: val.title,
            dimensions: val.dimensions.map(|t| {
                let arr: Vec<_> = [t.0, t.1].into_iter().map(|v| v as _).collect();
                arr
            }),
            image_count: val.image_count,
            table_count: val.table_count,
            hidden: val.hidden,
            is_blank: val.is_blank,
            has_vector_graphics: val.has_vector_graphics,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PageContent> for kreuzberg::PageContent {
    fn from(val: PageContent) -> Self {
        Self {
            page_number: val.page_number,
            content: val.content,
            tables: val.tables.into_iter().map(|v| std::sync::Arc::new(v.into())).collect(),
            image_indices: val.image_indices.into_iter().collect(),
            hierarchy: val.hierarchy.map(Into::into),
            is_blank: val.is_blank,
            layout_regions: val.layout_regions.map(|v| v.into_iter().map(Into::into).collect()),
            speaker_notes: val.speaker_notes,
            section_name: val.section_name,
            sheet_name: val.sheet_name,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PageContent> for PageContent {
    fn from(val: kreuzberg::PageContent) -> Self {
        Self {
            page_number: val.page_number,
            content: val.content,
            tables: val.tables.into_iter().map(|v| (*v).clone().into()).collect(),
            image_indices: val.image_indices.into_iter().collect(),
            hierarchy: val.hierarchy.map(Into::into),
            is_blank: val.is_blank,
            layout_regions: val.layout_regions.map(|v| v.into_iter().map(Into::into).collect()),
            speaker_notes: val.speaker_notes,
            section_name: val.section_name,
            sheet_name: val.sheet_name,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<LayoutRegion> for kreuzberg::LayoutRegion {
    fn from(val: LayoutRegion) -> Self {
        Self {
            class_name: val.class_name,
            confidence: val.confidence,
            bounding_box: val.bounding_box.into(),
            area_fraction: val.area_fraction,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::LayoutRegion> for LayoutRegion {
    fn from(val: kreuzberg::LayoutRegion) -> Self {
        Self {
            class_name: val.class_name,
            confidence: val.confidence,
            bounding_box: val.bounding_box.into(),
            area_fraction: val.area_fraction,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PageHierarchy> for kreuzberg::PageHierarchy {
    fn from(val: PageHierarchy) -> Self {
        Self {
            block_count: val.block_count,
            blocks: val.blocks.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PageHierarchy> for PageHierarchy {
    fn from(val: kreuzberg::PageHierarchy) -> Self {
        Self {
            block_count: val.block_count,
            blocks: val.blocks.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<HierarchicalBlock> for kreuzberg::HierarchicalBlock {
    fn from(val: HierarchicalBlock) -> Self {
        Self {
            text: val.text,
            font_size: val.font_size,
            level: val.level,
            bbox: Default::default(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::HierarchicalBlock> for HierarchicalBlock {
    fn from(val: kreuzberg::HierarchicalBlock) -> Self {
        Self {
            text: val.text,
            font_size: val.font_size,
            level: val.level,
            bbox: val.bbox.map(|t| {
                let arr: Vec<_> = [t.0, t.1].into_iter().map(|v| v as _).collect();
                arr
            }),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<CellChange> for kreuzberg::CellChange {
    fn from(val: CellChange) -> Self {
        Self {
            row: val.row,
            col: val.col,
            from: val.from_,
            to: val.to,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::CellChange> for CellChange {
    fn from(val: kreuzberg::CellChange) -> Self {
        Self {
            row: val.row,
            col: val.col,
            from_: val.from,
            to: val.to,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DocumentRevision> for kreuzberg::DocumentRevision {
    fn from(val: DocumentRevision) -> Self {
        Self {
            revision_id: val.revision_id,
            author: val.author,
            timestamp: val.timestamp,
            kind: val.kind.into(),
            anchor: val.anchor.map(Into::into),
            delta: val.delta.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DocumentRevision> for DocumentRevision {
    fn from(val: kreuzberg::DocumentRevision) -> Self {
        Self {
            revision_id: val.revision_id,
            author: val.author,
            timestamp: val.timestamp,
            kind: val.kind.into(),
            anchor: val.anchor.map(Into::into),
            delta: val.delta.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<RevisionDelta> for kreuzberg::RevisionDelta {
    fn from(val: RevisionDelta) -> Self {
        Self {
            content: val.content.into_iter().map(Into::into).collect(),
            table_changes: val.table_changes.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::RevisionDelta> for RevisionDelta {
    fn from(val: kreuzberg::RevisionDelta) -> Self {
        Self {
            content: val.content.into_iter().map(Into::into).collect(),
            table_changes: val.table_changes.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<Table> for kreuzberg::Table {
    fn from(val: Table) -> Self {
        Self {
            cells: val.cells.into_iter().collect(),
            markdown: val.markdown,
            page_number: val.page_number,
            bounding_box: val.bounding_box.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::Table> for Table {
    fn from(val: kreuzberg::Table) -> Self {
        Self {
            cells: val.cells.into_iter().collect(),
            markdown: val.markdown,
            page_number: val.page_number,
            bounding_box: val.bounding_box.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::TableCell> for TableCell {
    fn from(val: kreuzberg::TableCell) -> Self {
        Self {
            content: val.content,
            row_span: val.row_span,
            col_span: val.col_span,
            is_header: val.is_header,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ExtractedUri> for kreuzberg::ExtractedUri {
    fn from(val: ExtractedUri) -> Self {
        Self {
            url: val.url,
            label: val.label,
            page: val.page,
            kind: val.kind.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ExtractedUri> for ExtractedUri {
    fn from(val: kreuzberg::ExtractedUri) -> Self {
        Self {
            url: val.url,
            label: val.label,
            page: val.page,
            kind: val.kind.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::api::DetectResponse> for DetectResponse {
    fn from(val: kreuzberg::api::DetectResponse) -> Self {
        Self {
            mime_type: val.mime_type,
            filename: val.filename,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DiffOptions> for kreuzberg::DiffOptions {
    fn from(val: DiffOptions) -> Self {
        Self {
            include_metadata: val.include_metadata,
            include_embedded: val.include_embedded,
            max_content_chars: val.max_content_chars,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DiffOptions> for DiffOptions {
    fn from(val: kreuzberg::DiffOptions) -> Self {
        Self {
            include_metadata: val.include_metadata,
            include_embedded: val.include_embedded,
            max_content_chars: val.max_content_chars,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<ExtractionDiff> for kreuzberg::ExtractionDiff {
    fn from(val: ExtractionDiff) -> Self {
        Self {
            content_diff: val.content_diff.into_iter().map(Into::into).collect(),
            tables_added: val.tables_added.into_iter().map(Into::into).collect(),
            tables_removed: val.tables_removed.into_iter().map(Into::into).collect(),
            tables_changed: val.tables_changed.into_iter().map(Into::into).collect(),
            metadata_changed: serde_json::from_str(&val.metadata_changed).unwrap_or_default(),
            embedded_changes: val.embedded_changes.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ExtractionDiff> for ExtractionDiff {
    fn from(val: kreuzberg::ExtractionDiff) -> Self {
        Self {
            content_diff: val.content_diff.into_iter().map(Into::into).collect(),
            tables_added: val.tables_added.into_iter().map(Into::into).collect(),
            tables_removed: val.tables_removed.into_iter().map(Into::into).collect(),
            tables_changed: val.tables_changed.into_iter().map(Into::into).collect(),
            metadata_changed: val.metadata_changed.to_string(),
            embedded_changes: val.embedded_changes.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<DiffHunk> for kreuzberg::DiffHunk {
    fn from(val: DiffHunk) -> Self {
        Self {
            from_line: val.from_line,
            from_count: val.from_count,
            to_line: val.to_line,
            to_count: val.to_count,
            lines: val.lines.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DiffHunk> for DiffHunk {
    fn from(val: kreuzberg::DiffHunk) -> Self {
        Self {
            from_line: val.from_line,
            from_count: val.from_count,
            to_line: val.to_line,
            to_count: val.to_count,
            lines: val.lines.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<TableDiff> for kreuzberg::TableDiff {
    fn from(val: TableDiff) -> Self {
        Self {
            from_index: val.from_index,
            to_index: val.to_index,
            cell_changes: val.cell_changes.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::TableDiff> for TableDiff {
    fn from(val: kreuzberg::TableDiff) -> Self {
        Self {
            from_index: val.from_index,
            to_index: val.to_index,
            cell_changes: val.cell_changes.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<EmbeddedChanges> for kreuzberg::EmbeddedChanges {
    fn from(val: EmbeddedChanges) -> Self {
        Self {
            added: val.added.into_iter().map(Into::into).collect(),
            removed: val.removed.into_iter().map(Into::into).collect(),
            changed: val.changed.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::EmbeddedChanges> for EmbeddedChanges {
    fn from(val: kreuzberg::EmbeddedChanges) -> Self {
        Self {
            added: val.added.into_iter().map(Into::into).collect(),
            removed: val.removed.into_iter().map(Into::into).collect(),
            changed: val.changed.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<EmbeddedDiff> for kreuzberg::EmbeddedDiff {
    fn from(val: EmbeddedDiff) -> Self {
        Self {
            path: val.path,
            diff: Box::new(val.diff.into()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::EmbeddedDiff> for EmbeddedDiff {
    fn from(val: kreuzberg::EmbeddedDiff) -> Self {
        Self {
            path: val.path,
            diff: (*val.diff).into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<EmbeddingPreset> for kreuzberg::EmbeddingPreset {
    fn from(val: EmbeddingPreset) -> Self {
        Self {
            name: val.name,
            chunk_size: val.chunk_size,
            overlap: val.overlap,
            model_repo: val.model_repo,
            pooling: val.pooling,
            model_file: val.model_file,
            dimensions: val.dimensions,
            description: val.description,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::EmbeddingPreset> for EmbeddingPreset {
    fn from(val: kreuzberg::EmbeddingPreset) -> Self {
        Self {
            name: val.name,
            chunk_size: val.chunk_size,
            overlap: val.overlap,
            model_repo: val.model_repo,
            pooling: val.pooling,
            model_file: val.model_file,
            dimensions: val.dimensions,
            description: val.description,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<YakeParams> for kreuzberg::YakeParams {
    fn from(val: YakeParams) -> Self {
        Self {
            window_size: val.window_size,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::YakeParams> for YakeParams {
    fn from(val: kreuzberg::YakeParams) -> Self {
        Self {
            window_size: val.window_size,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<RakeParams> for kreuzberg::RakeParams {
    fn from(val: RakeParams) -> Self {
        Self {
            min_word_length: val.min_word_length,
            max_words_per_phrase: val.max_words_per_phrase,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::RakeParams> for RakeParams {
    fn from(val: kreuzberg::RakeParams) -> Self {
        Self {
            min_word_length: val.min_word_length,
            max_words_per_phrase: val.max_words_per_phrase,
        }
    }
}

#[allow(clippy::needless_update)]
#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<KeywordConfig> for kreuzberg::KeywordConfig {
    fn from(val: KeywordConfig) -> Self {
        Self {
            algorithm: val.algorithm.into(),
            max_keywords: val.max_keywords,
            min_score: val.min_score,
            ngram_range: Default::default(),
            language: val.language,
            yake_params: val.yake_params.map(Into::into),
            rake_params: val.rake_params.map(Into::into),
            ..Default::default()
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::KeywordConfig> for KeywordConfig {
    fn from(val: kreuzberg::KeywordConfig) -> Self {
        Self {
            algorithm: val.algorithm.into(),
            max_keywords: val.max_keywords,
            min_score: val.min_score,
            ngram_range: vec![val.ngram_range.0 as _, val.ngram_range.1 as _],
            language: val.language,
            yake_params: val.yake_params.map(Into::into),
            rake_params: val.rake_params.map(Into::into),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<Keyword> for kreuzberg::Keyword {
    fn from(val: Keyword) -> Self {
        Self {
            text: val.text,
            score: val.score,
            algorithm: val.algorithm.into(),
            positions: val.positions.map(|v| v.into_iter().collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::Keyword> for Keyword {
    fn from(val: kreuzberg::Keyword) -> Self {
        Self {
            text: val.text,
            score: val.score,
            algorithm: val.algorithm.into(),
            positions: val.positions.map(|v| v.into_iter().collect()),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PaddleOcrConfig> for kreuzberg::PaddleOcrConfig {
    fn from(val: PaddleOcrConfig) -> Self {
        Self {
            language: val.language,
            cache_dir: val.cache_dir.map(Into::into),
            use_angle_cls: val.use_angle_cls,
            enable_table_detection: val.enable_table_detection,
            det_db_thresh: val.det_db_thresh,
            det_db_box_thresh: val.det_db_box_thresh,
            det_db_unclip_ratio: val.det_db_unclip_ratio,
            det_limit_side_len: val.det_limit_side_len,
            rec_batch_num: val.rec_batch_num,
            padding: val.padding,
            drop_score: val.drop_score,
            model_tier: val.model_tier,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::PaddleOcrConfig> for PaddleOcrConfig {
    fn from(val: kreuzberg::PaddleOcrConfig) -> Self {
        Self {
            language: val.language,
            cache_dir: val.cache_dir.map(|p| p.to_string_lossy().to_string()),
            use_angle_cls: val.use_angle_cls,
            enable_table_detection: val.enable_table_detection,
            det_db_thresh: val.det_db_thresh,
            det_db_box_thresh: val.det_db_box_thresh,
            det_db_unclip_ratio: val.det_db_unclip_ratio,
            det_limit_side_len: val.det_limit_side_len,
            rec_batch_num: val.rec_batch_num,
            padding: val.padding,
            drop_score: val.drop_score,
            model_tier: val.model_tier,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::ModelPaths> for ModelPaths {
    fn from(val: kreuzberg::ModelPaths) -> Self {
        Self {
            det_model: val.det_model.to_string_lossy().to_string(),
            cls_model: val.cls_model.to_string_lossy().to_string(),
            rec_model: val.rec_model.to_string_lossy().to_string(),
            dict_file: val.dict_file.to_string_lossy().to_string(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::OrientationResult> for OrientationResult {
    fn from(val: kreuzberg::OrientationResult) -> Self {
        Self {
            degrees: val.degrees,
            confidence: val.confidence,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::BBox> for BBox {
    fn from(val: kreuzberg::BBox) -> Self {
        Self {
            x1: val.x1,
            y1: val.y1,
            x2: val.x2,
            y2: val.y2,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::LayoutDetection> for LayoutDetection {
    fn from(val: kreuzberg::LayoutDetection) -> Self {
        Self {
            class_name: val.class_name.into(),
            confidence: val.confidence,
            bbox: val.bbox.into(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::RecognizedTable> for RecognizedTable {
    fn from(val: kreuzberg::RecognizedTable) -> Self {
        Self {
            detection_bbox: val.detection_bbox.into(),
            cells: val.cells.into_iter().collect(),
            markdown: val.markdown,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::DetectionResult> for DetectionResult {
    fn from(val: kreuzberg::DetectionResult) -> Self {
        Self {
            page_width: val.page_width,
            page_height: val.page_height,
            detections: val.detections.into_iter().map(Into::into).collect(),
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::pdf::embedded_files::EmbeddedFile> for EmbeddedFile {
    fn from(val: kreuzberg::pdf::embedded_files::EmbeddedFile) -> Self {
        Self {
            name: val.name,
            data: val.data.to_vec().into(),
            compressed_size: val.compressed_size,
            mime_type: val.mime_type,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<PdfMetadata> for kreuzberg::pdf::metadata::PdfMetadata {
    fn from(val: PdfMetadata) -> Self {
        Self {
            pdf_version: val.pdf_version,
            producer: val.producer,
            is_encrypted: val.is_encrypted,
            width: val.width,
            height: val.height,
            page_count: val.page_count,
        }
    }
}

#[allow(clippy::redundant_closure, clippy::useless_conversion)]
impl From<kreuzberg::pdf::metadata::PdfMetadata> for PdfMetadata {
    fn from(val: kreuzberg::pdf::metadata::PdfMetadata) -> Self {
        Self {
            pdf_version: val.pdf_version,
            producer: val.producer,
            is_encrypted: val.is_encrypted,
            width: val.width,
            height: val.height,
            page_count: val.page_count,
        }
    }
}

impl From<ExecutionProviderType> for kreuzberg::ExecutionProviderType {
    fn from(val: ExecutionProviderType) -> Self {
        match val {
            ExecutionProviderType::Auto => Self::Auto,
            ExecutionProviderType::Cpu => Self::Cpu,
            ExecutionProviderType::CoreMl => Self::CoreMl,
            ExecutionProviderType::Cuda => Self::Cuda,
            ExecutionProviderType::TensorRt => Self::TensorRt,
        }
    }
}

impl From<kreuzberg::ExecutionProviderType> for ExecutionProviderType {
    fn from(val: kreuzberg::ExecutionProviderType) -> Self {
        match val {
            kreuzberg::ExecutionProviderType::Auto => Self::Auto,
            kreuzberg::ExecutionProviderType::Cpu => Self::Cpu,
            kreuzberg::ExecutionProviderType::CoreMl => Self::CoreMl,
            kreuzberg::ExecutionProviderType::Cuda => Self::Cuda,
            kreuzberg::ExecutionProviderType::TensorRt => Self::TensorRt,
        }
    }
}

impl From<HtmlTheme> for kreuzberg::HtmlTheme {
    fn from(val: HtmlTheme) -> Self {
        match val {
            HtmlTheme::Default => Self::Default,
            HtmlTheme::GitHub => Self::GitHub,
            HtmlTheme::Dark => Self::Dark,
            HtmlTheme::Light => Self::Light,
            HtmlTheme::Unstyled => Self::Unstyled,
        }
    }
}

impl From<kreuzberg::HtmlTheme> for HtmlTheme {
    fn from(val: kreuzberg::HtmlTheme) -> Self {
        match val {
            kreuzberg::HtmlTheme::Default => Self::Default,
            kreuzberg::HtmlTheme::GitHub => Self::GitHub,
            kreuzberg::HtmlTheme::Dark => Self::Dark,
            kreuzberg::HtmlTheme::Light => Self::Light,
            kreuzberg::HtmlTheme::Unstyled => Self::Unstyled,
        }
    }
}

impl From<TableModel> for kreuzberg::TableModel {
    fn from(val: TableModel) -> Self {
        match val {
            TableModel::Tatr => Self::Tatr,
            TableModel::SlanetWired => Self::SlanetWired,
            TableModel::SlanetWireless => Self::SlanetWireless,
            TableModel::SlanetPlus => Self::SlanetPlus,
            TableModel::SlanetAuto => Self::SlanetAuto,
            TableModel::Disabled => Self::Disabled,
        }
    }
}

impl From<kreuzberg::TableModel> for TableModel {
    fn from(val: kreuzberg::TableModel) -> Self {
        match val {
            kreuzberg::TableModel::Tatr => Self::Tatr,
            kreuzberg::TableModel::SlanetWired => Self::SlanetWired,
            kreuzberg::TableModel::SlanetWireless => Self::SlanetWireless,
            kreuzberg::TableModel::SlanetPlus => Self::SlanetPlus,
            kreuzberg::TableModel::SlanetAuto => Self::SlanetAuto,
            kreuzberg::TableModel::Disabled => Self::Disabled,
        }
    }
}

impl From<ChunkerType> for kreuzberg::ChunkerType {
    fn from(val: ChunkerType) -> Self {
        match val {
            ChunkerType::Text => Self::Text,
            ChunkerType::Markdown => Self::Markdown,
            ChunkerType::Yaml => Self::Yaml,
            ChunkerType::Semantic => Self::Semantic,
        }
    }
}

impl From<kreuzberg::ChunkerType> for ChunkerType {
    fn from(val: kreuzberg::ChunkerType) -> Self {
        match val {
            kreuzberg::ChunkerType::Text => Self::Text,
            kreuzberg::ChunkerType::Markdown => Self::Markdown,
            kreuzberg::ChunkerType::Yaml => Self::Yaml,
            kreuzberg::ChunkerType::Semantic => Self::Semantic,
        }
    }
}

impl From<CodeContentMode> for kreuzberg::CodeContentMode {
    fn from(val: CodeContentMode) -> Self {
        match val {
            CodeContentMode::Chunks => Self::Chunks,
            CodeContentMode::Raw => Self::Raw,
            CodeContentMode::Structure => Self::Structure,
        }
    }
}

impl From<kreuzberg::CodeContentMode> for CodeContentMode {
    fn from(val: kreuzberg::CodeContentMode) -> Self {
        match val {
            kreuzberg::CodeContentMode::Chunks => Self::Chunks,
            kreuzberg::CodeContentMode::Raw => Self::Raw,
            kreuzberg::CodeContentMode::Structure => Self::Structure,
        }
    }
}

impl From<kreuzberg::extraction::transform::ListType> for ListType {
    fn from(val: kreuzberg::extraction::transform::ListType) -> Self {
        match val {
            kreuzberg::extraction::transform::ListType::Bullet => Self::Bullet,
            kreuzberg::extraction::transform::ListType::Numbered => Self::Numbered,
            kreuzberg::extraction::transform::ListType::Lettered => Self::Lettered,
            kreuzberg::extraction::transform::ListType::Indented => Self::Indented,
        }
    }
}

impl From<kreuzberg::OcrBackendType> for OcrBackendType {
    fn from(val: kreuzberg::OcrBackendType) -> Self {
        match val {
            kreuzberg::OcrBackendType::Tesseract => Self::Tesseract,
            kreuzberg::OcrBackendType::EasyOCR => Self::EasyOCR,
            kreuzberg::OcrBackendType::PaddleOCR => Self::PaddleOCR,
            kreuzberg::OcrBackendType::Custom => Self::Custom,
        }
    }
}

impl From<kreuzberg::ProcessingStage> for ProcessingStage {
    fn from(val: kreuzberg::ProcessingStage) -> Self {
        match val {
            kreuzberg::ProcessingStage::Early => Self::Early,
            kreuzberg::ProcessingStage::Middle => Self::Middle,
            kreuzberg::ProcessingStage::Late => Self::Late,
        }
    }
}

impl From<ReductionLevel> for kreuzberg::ReductionLevel {
    fn from(val: ReductionLevel) -> Self {
        match val {
            ReductionLevel::Off => Self::Off,
            ReductionLevel::Light => Self::Light,
            ReductionLevel::Moderate => Self::Moderate,
            ReductionLevel::Aggressive => Self::Aggressive,
            ReductionLevel::Maximum => Self::Maximum,
        }
    }
}

impl From<kreuzberg::ReductionLevel> for ReductionLevel {
    fn from(val: kreuzberg::ReductionLevel) -> Self {
        match val {
            kreuzberg::ReductionLevel::Off => Self::Off,
            kreuzberg::ReductionLevel::Light => Self::Light,
            kreuzberg::ReductionLevel::Moderate => Self::Moderate,
            kreuzberg::ReductionLevel::Aggressive => Self::Aggressive,
            kreuzberg::ReductionLevel::Maximum => Self::Maximum,
        }
    }
}

impl From<PdfAnnotationType> for kreuzberg::PdfAnnotationType {
    fn from(val: PdfAnnotationType) -> Self {
        match val {
            PdfAnnotationType::Text => Self::Text,
            PdfAnnotationType::Highlight => Self::Highlight,
            PdfAnnotationType::Link => Self::Link,
            PdfAnnotationType::Stamp => Self::Stamp,
            PdfAnnotationType::Underline => Self::Underline,
            PdfAnnotationType::StrikeOut => Self::StrikeOut,
            PdfAnnotationType::Other => Self::Other,
        }
    }
}

impl From<kreuzberg::PdfAnnotationType> for PdfAnnotationType {
    fn from(val: kreuzberg::PdfAnnotationType) -> Self {
        match val {
            kreuzberg::PdfAnnotationType::Text => Self::Text,
            kreuzberg::PdfAnnotationType::Highlight => Self::Highlight,
            kreuzberg::PdfAnnotationType::Link => Self::Link,
            kreuzberg::PdfAnnotationType::Stamp => Self::Stamp,
            kreuzberg::PdfAnnotationType::Underline => Self::Underline,
            kreuzberg::PdfAnnotationType::StrikeOut => Self::StrikeOut,
            kreuzberg::PdfAnnotationType::Other => Self::Other,
        }
    }
}

impl From<BlockType> for kreuzberg::BlockType {
    fn from(val: BlockType) -> Self {
        match val {
            BlockType::Paragraph => Self::Paragraph,
            BlockType::Heading => Self::Heading,
            BlockType::Blockquote => Self::Blockquote,
            BlockType::CodeBlock => Self::CodeBlock,
            BlockType::ListItem => Self::ListItem,
            BlockType::OrderedList => Self::OrderedList,
            BlockType::BulletList => Self::BulletList,
            BlockType::TaskList => Self::TaskList,
            BlockType::DefinitionList => Self::DefinitionList,
            BlockType::DefinitionTerm => Self::DefinitionTerm,
            BlockType::DefinitionDescription => Self::DefinitionDescription,
            BlockType::Div => Self::Div,
            BlockType::Section => Self::Section,
            BlockType::ThematicBreak => Self::ThematicBreak,
            BlockType::RawBlock => Self::RawBlock,
            BlockType::MathDisplay => Self::MathDisplay,
        }
    }
}

impl From<kreuzberg::BlockType> for BlockType {
    fn from(val: kreuzberg::BlockType) -> Self {
        match val {
            kreuzberg::BlockType::Paragraph => Self::Paragraph,
            kreuzberg::BlockType::Heading => Self::Heading,
            kreuzberg::BlockType::Blockquote => Self::Blockquote,
            kreuzberg::BlockType::CodeBlock => Self::CodeBlock,
            kreuzberg::BlockType::ListItem => Self::ListItem,
            kreuzberg::BlockType::OrderedList => Self::OrderedList,
            kreuzberg::BlockType::BulletList => Self::BulletList,
            kreuzberg::BlockType::TaskList => Self::TaskList,
            kreuzberg::BlockType::DefinitionList => Self::DefinitionList,
            kreuzberg::BlockType::DefinitionTerm => Self::DefinitionTerm,
            kreuzberg::BlockType::DefinitionDescription => Self::DefinitionDescription,
            kreuzberg::BlockType::Div => Self::Div,
            kreuzberg::BlockType::Section => Self::Section,
            kreuzberg::BlockType::ThematicBreak => Self::ThematicBreak,
            kreuzberg::BlockType::RawBlock => Self::RawBlock,
            kreuzberg::BlockType::MathDisplay => Self::MathDisplay,
        }
    }
}

impl From<InlineType> for kreuzberg::InlineType {
    fn from(val: InlineType) -> Self {
        match val {
            InlineType::Text => Self::Text,
            InlineType::Strong => Self::Strong,
            InlineType::Emphasis => Self::Emphasis,
            InlineType::Highlight => Self::Highlight,
            InlineType::Subscript => Self::Subscript,
            InlineType::Superscript => Self::Superscript,
            InlineType::Insert => Self::Insert,
            InlineType::Delete => Self::Delete,
            InlineType::Code => Self::Code,
            InlineType::Link => Self::Link,
            InlineType::Image => Self::Image,
            InlineType::Span => Self::Span,
            InlineType::Math => Self::Math,
            InlineType::RawInline => Self::RawInline,
            InlineType::FootnoteRef => Self::FootnoteRef,
            InlineType::Symbol => Self::Symbol,
        }
    }
}

impl From<kreuzberg::InlineType> for InlineType {
    fn from(val: kreuzberg::InlineType) -> Self {
        match val {
            kreuzberg::InlineType::Text => Self::Text,
            kreuzberg::InlineType::Strong => Self::Strong,
            kreuzberg::InlineType::Emphasis => Self::Emphasis,
            kreuzberg::InlineType::Highlight => Self::Highlight,
            kreuzberg::InlineType::Subscript => Self::Subscript,
            kreuzberg::InlineType::Superscript => Self::Superscript,
            kreuzberg::InlineType::Insert => Self::Insert,
            kreuzberg::InlineType::Delete => Self::Delete,
            kreuzberg::InlineType::Code => Self::Code,
            kreuzberg::InlineType::Link => Self::Link,
            kreuzberg::InlineType::Image => Self::Image,
            kreuzberg::InlineType::Span => Self::Span,
            kreuzberg::InlineType::Math => Self::Math,
            kreuzberg::InlineType::RawInline => Self::RawInline,
            kreuzberg::InlineType::FootnoteRef => Self::FootnoteRef,
            kreuzberg::InlineType::Symbol => Self::Symbol,
        }
    }
}

impl From<RelationshipKind> for kreuzberg::RelationshipKind {
    fn from(val: RelationshipKind) -> Self {
        match val {
            RelationshipKind::FootnoteReference => Self::FootnoteReference,
            RelationshipKind::CitationReference => Self::CitationReference,
            RelationshipKind::InternalLink => Self::InternalLink,
            RelationshipKind::Caption => Self::Caption,
            RelationshipKind::Label => Self::Label,
            RelationshipKind::TocEntry => Self::TocEntry,
            RelationshipKind::CrossReference => Self::CrossReference,
        }
    }
}

impl From<kreuzberg::RelationshipKind> for RelationshipKind {
    fn from(val: kreuzberg::RelationshipKind) -> Self {
        match val {
            kreuzberg::RelationshipKind::FootnoteReference => Self::FootnoteReference,
            kreuzberg::RelationshipKind::CitationReference => Self::CitationReference,
            kreuzberg::RelationshipKind::InternalLink => Self::InternalLink,
            kreuzberg::RelationshipKind::Caption => Self::Caption,
            kreuzberg::RelationshipKind::Label => Self::Label,
            kreuzberg::RelationshipKind::TocEntry => Self::TocEntry,
            kreuzberg::RelationshipKind::CrossReference => Self::CrossReference,
        }
    }
}

impl From<ContentLayer> for kreuzberg::ContentLayer {
    fn from(val: ContentLayer) -> Self {
        match val {
            ContentLayer::Body => Self::Body,
            ContentLayer::Header => Self::Header,
            ContentLayer::Footer => Self::Footer,
            ContentLayer::Footnote => Self::Footnote,
        }
    }
}

impl From<kreuzberg::ContentLayer> for ContentLayer {
    fn from(val: kreuzberg::ContentLayer) -> Self {
        match val {
            kreuzberg::ContentLayer::Body => Self::Body,
            kreuzberg::ContentLayer::Header => Self::Header,
            kreuzberg::ContentLayer::Footer => Self::Footer,
            kreuzberg::ContentLayer::Footnote => Self::Footnote,
        }
    }
}

impl From<ExtractionMethod> for kreuzberg::ExtractionMethod {
    fn from(val: ExtractionMethod) -> Self {
        match val {
            ExtractionMethod::Native => Self::Native,
            ExtractionMethod::Ocr => Self::Ocr,
            ExtractionMethod::Mixed => Self::Mixed,
        }
    }
}

impl From<kreuzberg::ExtractionMethod> for ExtractionMethod {
    fn from(val: kreuzberg::ExtractionMethod) -> Self {
        match val {
            kreuzberg::ExtractionMethod::Native => Self::Native,
            kreuzberg::ExtractionMethod::Ocr => Self::Ocr,
            kreuzberg::ExtractionMethod::Mixed => Self::Mixed,
        }
    }
}

impl From<ChunkType> for kreuzberg::ChunkType {
    fn from(val: ChunkType) -> Self {
        match val {
            ChunkType::Heading => Self::Heading,
            ChunkType::PartyList => Self::PartyList,
            ChunkType::Definitions => Self::Definitions,
            ChunkType::OperativeClause => Self::OperativeClause,
            ChunkType::SignatureBlock => Self::SignatureBlock,
            ChunkType::Schedule => Self::Schedule,
            ChunkType::TableLike => Self::TableLike,
            ChunkType::Formula => Self::Formula,
            ChunkType::CodeBlock => Self::CodeBlock,
            ChunkType::Image => Self::Image,
            ChunkType::OrgChart => Self::OrgChart,
            ChunkType::Diagram => Self::Diagram,
            ChunkType::Unknown => Self::Unknown,
        }
    }
}

impl From<kreuzberg::ChunkType> for ChunkType {
    fn from(val: kreuzberg::ChunkType) -> Self {
        match val {
            kreuzberg::ChunkType::Heading => Self::Heading,
            kreuzberg::ChunkType::PartyList => Self::PartyList,
            kreuzberg::ChunkType::Definitions => Self::Definitions,
            kreuzberg::ChunkType::OperativeClause => Self::OperativeClause,
            kreuzberg::ChunkType::SignatureBlock => Self::SignatureBlock,
            kreuzberg::ChunkType::Schedule => Self::Schedule,
            kreuzberg::ChunkType::TableLike => Self::TableLike,
            kreuzberg::ChunkType::Formula => Self::Formula,
            kreuzberg::ChunkType::CodeBlock => Self::CodeBlock,
            kreuzberg::ChunkType::Image => Self::Image,
            kreuzberg::ChunkType::OrgChart => Self::OrgChart,
            kreuzberg::ChunkType::Diagram => Self::Diagram,
            kreuzberg::ChunkType::Unknown => Self::Unknown,
        }
    }
}

impl From<ImageKind> for kreuzberg::ImageKind {
    fn from(val: ImageKind) -> Self {
        match val {
            ImageKind::Photograph => Self::Photograph,
            ImageKind::Diagram => Self::Diagram,
            ImageKind::Chart => Self::Chart,
            ImageKind::Drawing => Self::Drawing,
            ImageKind::TextBlock => Self::TextBlock,
            ImageKind::Decoration => Self::Decoration,
            ImageKind::Logo => Self::Logo,
            ImageKind::Icon => Self::Icon,
            ImageKind::TileFragment => Self::TileFragment,
            ImageKind::Mask => Self::Mask,
            ImageKind::PageRaster => Self::PageRaster,
            ImageKind::Unknown => Self::Unknown,
        }
    }
}

impl From<kreuzberg::ImageKind> for ImageKind {
    fn from(val: kreuzberg::ImageKind) -> Self {
        match val {
            kreuzberg::ImageKind::Photograph => Self::Photograph,
            kreuzberg::ImageKind::Diagram => Self::Diagram,
            kreuzberg::ImageKind::Chart => Self::Chart,
            kreuzberg::ImageKind::Drawing => Self::Drawing,
            kreuzberg::ImageKind::TextBlock => Self::TextBlock,
            kreuzberg::ImageKind::Decoration => Self::Decoration,
            kreuzberg::ImageKind::Logo => Self::Logo,
            kreuzberg::ImageKind::Icon => Self::Icon,
            kreuzberg::ImageKind::TileFragment => Self::TileFragment,
            kreuzberg::ImageKind::Mask => Self::Mask,
            kreuzberg::ImageKind::PageRaster => Self::PageRaster,
            kreuzberg::ImageKind::Unknown => Self::Unknown,
        }
    }
}

impl From<ResultFormat> for kreuzberg::ResultFormat {
    fn from(val: ResultFormat) -> Self {
        match val {
            ResultFormat::Unified => Self::Unified,
            ResultFormat::ElementBased => Self::ElementBased,
        }
    }
}

impl From<kreuzberg::ResultFormat> for ResultFormat {
    fn from(val: kreuzberg::ResultFormat) -> Self {
        match val {
            kreuzberg::ResultFormat::Unified => Self::Unified,
            kreuzberg::ResultFormat::ElementBased => Self::ElementBased,
        }
    }
}

impl From<ElementType> for kreuzberg::ElementType {
    fn from(val: ElementType) -> Self {
        match val {
            ElementType::Title => Self::Title,
            ElementType::NarrativeText => Self::NarrativeText,
            ElementType::Heading => Self::Heading,
            ElementType::ListItem => Self::ListItem,
            ElementType::Table => Self::Table,
            ElementType::Image => Self::Image,
            ElementType::PageBreak => Self::PageBreak,
            ElementType::CodeBlock => Self::CodeBlock,
            ElementType::BlockQuote => Self::BlockQuote,
            ElementType::Footer => Self::Footer,
            ElementType::Header => Self::Header,
        }
    }
}

impl From<kreuzberg::ElementType> for ElementType {
    fn from(val: kreuzberg::ElementType) -> Self {
        match val {
            kreuzberg::ElementType::Title => Self::Title,
            kreuzberg::ElementType::NarrativeText => Self::NarrativeText,
            kreuzberg::ElementType::Heading => Self::Heading,
            kreuzberg::ElementType::ListItem => Self::ListItem,
            kreuzberg::ElementType::Table => Self::Table,
            kreuzberg::ElementType::Image => Self::Image,
            kreuzberg::ElementType::PageBreak => Self::PageBreak,
            kreuzberg::ElementType::CodeBlock => Self::CodeBlock,
            kreuzberg::ElementType::BlockQuote => Self::BlockQuote,
            kreuzberg::ElementType::Footer => Self::Footer,
            kreuzberg::ElementType::Header => Self::Header,
        }
    }
}

impl From<TextDirection> for kreuzberg::TextDirection {
    fn from(val: TextDirection) -> Self {
        match val {
            TextDirection::LeftToRight => Self::LeftToRight,
            TextDirection::RightToLeft => Self::RightToLeft,
            TextDirection::Auto => Self::Auto,
        }
    }
}

impl From<kreuzberg::TextDirection> for TextDirection {
    fn from(val: kreuzberg::TextDirection) -> Self {
        match val {
            kreuzberg::TextDirection::LeftToRight => Self::LeftToRight,
            kreuzberg::TextDirection::RightToLeft => Self::RightToLeft,
            kreuzberg::TextDirection::Auto => Self::Auto,
        }
    }
}

impl From<LinkType> for kreuzberg::LinkType {
    fn from(val: LinkType) -> Self {
        match val {
            LinkType::Anchor => Self::Anchor,
            LinkType::Internal => Self::Internal,
            LinkType::External => Self::External,
            LinkType::Email => Self::Email,
            LinkType::Phone => Self::Phone,
            LinkType::Other => Self::Other,
        }
    }
}

impl From<kreuzberg::LinkType> for LinkType {
    fn from(val: kreuzberg::LinkType) -> Self {
        match val {
            kreuzberg::LinkType::Anchor => Self::Anchor,
            kreuzberg::LinkType::Internal => Self::Internal,
            kreuzberg::LinkType::External => Self::External,
            kreuzberg::LinkType::Email => Self::Email,
            kreuzberg::LinkType::Phone => Self::Phone,
            kreuzberg::LinkType::Other => Self::Other,
        }
    }
}

impl From<ImageType> for kreuzberg::ImageType {
    fn from(val: ImageType) -> Self {
        match val {
            ImageType::DataUri => Self::DataUri,
            ImageType::InlineSvg => Self::InlineSvg,
            ImageType::External => Self::External,
            ImageType::Relative => Self::Relative,
        }
    }
}

impl From<kreuzberg::ImageType> for ImageType {
    fn from(val: kreuzberg::ImageType) -> Self {
        match val {
            kreuzberg::ImageType::DataUri => Self::DataUri,
            kreuzberg::ImageType::InlineSvg => Self::InlineSvg,
            kreuzberg::ImageType::External => Self::External,
            kreuzberg::ImageType::Relative => Self::Relative,
        }
    }
}

impl From<StructuredDataType> for kreuzberg::StructuredDataType {
    fn from(val: StructuredDataType) -> Self {
        match val {
            StructuredDataType::JsonLd => Self::JsonLd,
            StructuredDataType::Microdata => Self::Microdata,
            StructuredDataType::RDFa => Self::RDFa,
        }
    }
}

impl From<kreuzberg::StructuredDataType> for StructuredDataType {
    fn from(val: kreuzberg::StructuredDataType) -> Self {
        match val {
            kreuzberg::StructuredDataType::JsonLd => Self::JsonLd,
            kreuzberg::StructuredDataType::Microdata => Self::Microdata,
            kreuzberg::StructuredDataType::RDFa => Self::RDFa,
        }
    }
}

impl From<OcrElementLevel> for kreuzberg::OcrElementLevel {
    fn from(val: OcrElementLevel) -> Self {
        match val {
            OcrElementLevel::Word => Self::Word,
            OcrElementLevel::Line => Self::Line,
            OcrElementLevel::Block => Self::Block,
            OcrElementLevel::Page => Self::Page,
        }
    }
}

impl From<kreuzberg::OcrElementLevel> for OcrElementLevel {
    fn from(val: kreuzberg::OcrElementLevel) -> Self {
        match val {
            kreuzberg::OcrElementLevel::Word => Self::Word,
            kreuzberg::OcrElementLevel::Line => Self::Line,
            kreuzberg::OcrElementLevel::Block => Self::Block,
            kreuzberg::OcrElementLevel::Page => Self::Page,
        }
    }
}

impl From<PageUnitType> for kreuzberg::PageUnitType {
    fn from(val: PageUnitType) -> Self {
        match val {
            PageUnitType::Page => Self::Page,
            PageUnitType::Slide => Self::Slide,
            PageUnitType::Sheet => Self::Sheet,
        }
    }
}

impl From<kreuzberg::PageUnitType> for PageUnitType {
    fn from(val: kreuzberg::PageUnitType) -> Self {
        match val {
            kreuzberg::PageUnitType::Page => Self::Page,
            kreuzberg::PageUnitType::Slide => Self::Slide,
            kreuzberg::PageUnitType::Sheet => Self::Sheet,
        }
    }
}

impl From<RevisionKind> for kreuzberg::RevisionKind {
    fn from(val: RevisionKind) -> Self {
        match val {
            RevisionKind::Insertion => Self::Insertion,
            RevisionKind::Deletion => Self::Deletion,
            RevisionKind::FormatChange => Self::FormatChange,
            RevisionKind::Comment => Self::Comment,
        }
    }
}

impl From<kreuzberg::RevisionKind> for RevisionKind {
    fn from(val: kreuzberg::RevisionKind) -> Self {
        match val {
            kreuzberg::RevisionKind::Insertion => Self::Insertion,
            kreuzberg::RevisionKind::Deletion => Self::Deletion,
            kreuzberg::RevisionKind::FormatChange => Self::FormatChange,
            kreuzberg::RevisionKind::Comment => Self::Comment,
        }
    }
}

impl From<UriKind> for kreuzberg::UriKind {
    fn from(val: UriKind) -> Self {
        match val {
            UriKind::Hyperlink => Self::Hyperlink,
            UriKind::Image => Self::Image,
            UriKind::Anchor => Self::Anchor,
            UriKind::Citation => Self::Citation,
            UriKind::Reference => Self::Reference,
            UriKind::Email => Self::Email,
        }
    }
}

impl From<kreuzberg::UriKind> for UriKind {
    fn from(val: kreuzberg::UriKind) -> Self {
        match val {
            kreuzberg::UriKind::Hyperlink => Self::Hyperlink,
            kreuzberg::UriKind::Image => Self::Image,
            kreuzberg::UriKind::Anchor => Self::Anchor,
            kreuzberg::UriKind::Citation => Self::Citation,
            kreuzberg::UriKind::Reference => Self::Reference,
            kreuzberg::UriKind::Email => Self::Email,
        }
    }
}

impl From<KeywordAlgorithm> for kreuzberg::KeywordAlgorithm {
    fn from(val: KeywordAlgorithm) -> Self {
        match val {
            KeywordAlgorithm::Yake => Self::Yake,
            KeywordAlgorithm::Rake => Self::Rake,
        }
    }
}

impl From<kreuzberg::KeywordAlgorithm> for KeywordAlgorithm {
    fn from(val: kreuzberg::KeywordAlgorithm) -> Self {
        match val {
            kreuzberg::KeywordAlgorithm::Yake => Self::Yake,
            kreuzberg::KeywordAlgorithm::Rake => Self::Rake,
        }
    }
}

impl From<kreuzberg::PSMMode> for PSMMode {
    fn from(val: kreuzberg::PSMMode) -> Self {
        match val {
            kreuzberg::PSMMode::OsdOnly => Self::OsdOnly,
            kreuzberg::PSMMode::AutoOsd => Self::AutoOsd,
            kreuzberg::PSMMode::AutoOnly => Self::AutoOnly,
            kreuzberg::PSMMode::Auto => Self::Auto,
            kreuzberg::PSMMode::SingleColumn => Self::SingleColumn,
            kreuzberg::PSMMode::SingleBlockVertical => Self::SingleBlockVertical,
            kreuzberg::PSMMode::SingleBlock => Self::SingleBlock,
            kreuzberg::PSMMode::SingleLine => Self::SingleLine,
            kreuzberg::PSMMode::SingleWord => Self::SingleWord,
            kreuzberg::PSMMode::CircleWord => Self::CircleWord,
            kreuzberg::PSMMode::SingleChar => Self::SingleChar,
        }
    }
}

impl From<kreuzberg::PaddleLanguage> for PaddleLanguage {
    fn from(val: kreuzberg::PaddleLanguage) -> Self {
        match val {
            kreuzberg::PaddleLanguage::English => Self::English,
            kreuzberg::PaddleLanguage::Chinese => Self::Chinese,
            kreuzberg::PaddleLanguage::Japanese => Self::Japanese,
            kreuzberg::PaddleLanguage::Korean => Self::Korean,
            kreuzberg::PaddleLanguage::German => Self::German,
            kreuzberg::PaddleLanguage::French => Self::French,
            kreuzberg::PaddleLanguage::Latin => Self::Latin,
            kreuzberg::PaddleLanguage::Cyrillic => Self::Cyrillic,
            kreuzberg::PaddleLanguage::TraditionalChinese => Self::TraditionalChinese,
            kreuzberg::PaddleLanguage::Thai => Self::Thai,
            kreuzberg::PaddleLanguage::Greek => Self::Greek,
            kreuzberg::PaddleLanguage::EastSlavic => Self::EastSlavic,
            kreuzberg::PaddleLanguage::Arabic => Self::Arabic,
            kreuzberg::PaddleLanguage::Devanagari => Self::Devanagari,
            kreuzberg::PaddleLanguage::Tamil => Self::Tamil,
            kreuzberg::PaddleLanguage::Telugu => Self::Telugu,
        }
    }
}

impl From<kreuzberg::LayoutClass> for LayoutClass {
    fn from(val: kreuzberg::LayoutClass) -> Self {
        match val {
            kreuzberg::LayoutClass::Caption => Self::Caption,
            kreuzberg::LayoutClass::Footnote => Self::Footnote,
            kreuzberg::LayoutClass::Formula => Self::Formula,
            kreuzberg::LayoutClass::ListItem => Self::ListItem,
            kreuzberg::LayoutClass::PageFooter => Self::PageFooter,
            kreuzberg::LayoutClass::PageHeader => Self::PageHeader,
            kreuzberg::LayoutClass::Picture => Self::Picture,
            kreuzberg::LayoutClass::SectionHeader => Self::SectionHeader,
            kreuzberg::LayoutClass::Table => Self::Table,
            kreuzberg::LayoutClass::Text => Self::Text,
            kreuzberg::LayoutClass::Title => Self::Title,
            kreuzberg::LayoutClass::DocumentIndex => Self::DocumentIndex,
            kreuzberg::LayoutClass::Code => Self::Code,
            kreuzberg::LayoutClass::CheckboxSelected => Self::CheckboxSelected,
            kreuzberg::LayoutClass::CheckboxUnselected => Self::CheckboxUnselected,
            kreuzberg::LayoutClass::Form => Self::Form,
            kreuzberg::LayoutClass::KeyValueRegion => Self::KeyValueRegion,
        }
    }
}

#[pyfunction]
pub fn init_async_runtime() -> PyResult<()> {
    // Tokio runtime auto-initializes on first future_into_py call
    Ok(())
}

#[pymodule]
pub fn _kreuzberg(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(init_async_runtime, m)?)?;
    m.add_class::<CacheStats>()?;
    m.add_class::<AccelerationConfig>()?;
    m.add_class::<ContentFilterConfig>()?;
    m.add_class::<EmailConfig>()?;
    m.add_class::<ExtractionConfig>()?;
    m.add_class::<FileExtractionConfig>()?;
    m.add_class::<BatchBytesItem>()?;
    m.add_class::<BatchFileItem>()?;
    m.add_class::<ImageExtractionConfig>()?;
    m.add_class::<TokenReductionOptions>()?;
    m.add_class::<LanguageDetectionConfig>()?;
    m.add_class::<HtmlOutputConfig>()?;
    m.add_class::<LayoutDetectionConfig>()?;
    m.add_class::<LlmConfig>()?;
    m.add_class::<StructuredExtractionConfig>()?;
    m.add_class::<OcrQualityThresholds>()?;
    m.add_class::<OcrPipelineStage>()?;
    m.add_class::<OcrPipelineConfig>()?;
    m.add_class::<OcrConfig>()?;
    m.add_class::<PageConfig>()?;
    m.add_class::<PdfConfig>()?;
    m.add_class::<HierarchyConfig>()?;
    m.add_class::<PostProcessorConfig>()?;
    m.add_class::<ChunkingConfig>()?;
    m.add_class::<EmbeddingConfig>()?;
    m.add_class::<TreeSitterConfig>()?;
    m.add_class::<TreeSitterProcessConfig>()?;
    m.add_class::<SupportedFormat>()?;
    m.add_class::<ServerConfig>()?;
    m.add_class::<StructuredDataResult>()?;
    m.add_class::<DocxAppProperties>()?;
    m.add_class::<XlsxAppProperties>()?;
    m.add_class::<PptxAppProperties>()?;
    m.add_class::<CoreProperties>()?;
    m.add_class::<SecurityLimits>()?;
    m.add_class::<TokenReductionConfig>()?;
    m.add_class::<PdfAnnotation>()?;
    m.add_class::<DjotContent>()?;
    m.add_class::<FormattedBlock>()?;
    m.add_class::<InlineElement>()?;
    m.add_class::<DjotImage>()?;
    m.add_class::<DjotLink>()?;
    m.add_class::<Footnote>()?;
    m.add_class::<DocumentStructure>()?;
    m.add_class::<DocumentRelationship>()?;
    m.add_class::<DocumentNode>()?;
    m.add_class::<TableGrid>()?;
    m.add_class::<GridCell>()?;
    m.add_class::<TextAnnotation>()?;
    m.add_class::<ExtractionResult>()?;
    m.add_class::<ArchiveEntry>()?;
    m.add_class::<ProcessingWarning>()?;
    m.add_class::<LlmUsage>()?;
    m.add_class::<Chunk>()?;
    m.add_class::<HeadingContext>()?;
    m.add_class::<HeadingLevel>()?;
    m.add_class::<ChunkMetadata>()?;
    m.add_class::<ExtractedImage>()?;
    m.add_class::<BoundingBox>()?;
    m.add_class::<ElementMetadata>()?;
    m.add_class::<Element>()?;
    m.add_class::<ExcelWorkbook>()?;
    m.add_class::<ExcelSheet>()?;
    m.add_class::<XmlExtractionResult>()?;
    m.add_class::<TextExtractionResult>()?;
    m.add_class::<PptxExtractionResult>()?;
    m.add_class::<EmailExtractionResult>()?;
    m.add_class::<EmailAttachment>()?;
    m.add_class::<OcrExtractionResult>()?;
    m.add_class::<OcrTable>()?;
    m.add_class::<OcrTableBoundingBox>()?;
    m.add_class::<ImagePreprocessingConfig>()?;
    m.add_class::<TesseractConfig>()?;
    m.add_class::<ImagePreprocessingMetadata>()?;
    m.add_class::<Metadata>()?;
    m.add_class::<ExcelMetadata>()?;
    m.add_class::<EmailMetadata>()?;
    m.add_class::<ArchiveMetadata>()?;
    m.add_class::<ImageMetadata>()?;
    m.add_class::<XmlMetadata>()?;
    m.add_class::<TextMetadata>()?;
    m.add_class::<HeaderMetadata>()?;
    m.add_class::<LinkMetadata>()?;
    m.add_class::<ImageMetadataType>()?;
    m.add_class::<StructuredData>()?;
    m.add_class::<HtmlMetadata>()?;
    m.add_class::<OcrMetadata>()?;
    m.add_class::<ErrorMetadata>()?;
    m.add_class::<PptxMetadata>()?;
    m.add_class::<DocxMetadata>()?;
    m.add_class::<CsvMetadata>()?;
    m.add_class::<BibtexMetadata>()?;
    m.add_class::<CitationMetadata>()?;
    m.add_class::<YearRange>()?;
    m.add_class::<FictionBookMetadata>()?;
    m.add_class::<DbfMetadata>()?;
    m.add_class::<DbfFieldInfo>()?;
    m.add_class::<JatsMetadata>()?;
    m.add_class::<ContributorRole>()?;
    m.add_class::<EpubMetadata>()?;
    m.add_class::<PstMetadata>()?;
    m.add_class::<OcrConfidence>()?;
    m.add_class::<OcrRotation>()?;
    m.add_class::<OcrElement>()?;
    m.add_class::<OcrElementConfig>()?;
    m.add_class::<PageStructure>()?;
    m.add_class::<PageBoundary>()?;
    m.add_class::<PageInfo>()?;
    m.add_class::<PageContent>()?;
    m.add_class::<LayoutRegion>()?;
    m.add_class::<PageHierarchy>()?;
    m.add_class::<HierarchicalBlock>()?;
    m.add_class::<CellChange>()?;
    m.add_class::<DocumentRevision>()?;
    m.add_class::<RevisionDelta>()?;
    m.add_class::<Table>()?;
    m.add_class::<TableCell>()?;
    m.add_class::<ExtractedUri>()?;
    m.add_class::<DetectResponse>()?;
    m.add_class::<DiffOptions>()?;
    m.add_class::<ExtractionDiff>()?;
    m.add_class::<DiffHunk>()?;
    m.add_class::<TableDiff>()?;
    m.add_class::<EmbeddedChanges>()?;
    m.add_class::<EmbeddedDiff>()?;
    m.add_class::<EmbeddingPreset>()?;
    m.add_class::<YakeParams>()?;
    m.add_class::<RakeParams>()?;
    m.add_class::<KeywordConfig>()?;
    m.add_class::<Keyword>()?;
    m.add_class::<PaddleOcrConfig>()?;
    m.add_class::<ModelPaths>()?;
    m.add_class::<OrientationResult>()?;
    m.add_class::<BBox>()?;
    m.add_class::<LayoutDetection>()?;
    m.add_class::<RecognizedTable>()?;
    m.add_class::<DetectionResult>()?;
    m.add_class::<EmbeddedFile>()?;
    m.add_class::<PdfMetadata>()?;
    m.add_class::<ExecutionProviderType>()?;
    m.add_class::<OutputFormat>()?;
    m.add_class::<HtmlTheme>()?;
    m.add_class::<TableModel>()?;
    m.add_class::<ChunkerType>()?;
    m.add_class::<ChunkSizing>()?;
    m.add_class::<EmbeddingModelType>()?;
    m.add_class::<CodeContentMode>()?;
    m.add_class::<ListType>()?;
    m.add_class::<OcrBackendType>()?;
    m.add_class::<ProcessingStage>()?;
    m.add_class::<ReductionLevel>()?;
    m.add_class::<PdfAnnotationType>()?;
    m.add_class::<BlockType>()?;
    m.add_class::<InlineType>()?;
    m.add_class::<RelationshipKind>()?;
    m.add_class::<ContentLayer>()?;
    m.add_class::<NodeContent>()?;
    m.add_class::<AnnotationKind>()?;
    m.add_class::<ExtractionMethod>()?;
    m.add_class::<ChunkType>()?;
    m.add_class::<ImageKind>()?;
    m.add_class::<ResultFormat>()?;
    m.add_class::<ElementType>()?;
    m.add_class::<FormatMetadata>()?;
    m.add_class::<TextDirection>()?;
    m.add_class::<LinkType>()?;
    m.add_class::<ImageType>()?;
    m.add_class::<StructuredDataType>()?;
    m.add_class::<OcrBoundingGeometry>()?;
    m.add_class::<OcrElementLevel>()?;
    m.add_class::<PageUnitType>()?;
    m.add_class::<DiffLine>()?;
    m.add_class::<RevisionKind>()?;
    m.add_class::<RevisionAnchor>()?;
    m.add_class::<UriKind>()?;
    m.add_class::<KeywordAlgorithm>()?;
    m.add_class::<PSMMode>()?;
    m.add_class::<PaddleLanguage>()?;
    m.add_class::<LayoutClass>()?;
    m.add_function(wrap_pyfunction!(extract_bytes, m)?)?;
    m.add_function(wrap_pyfunction!(extract_file, m)?)?;
    m.add_function(wrap_pyfunction!(extract_file_sync, m)?)?;
    m.add_function(wrap_pyfunction!(extract_bytes_sync, m)?)?;
    m.add_function(wrap_pyfunction!(batch_extract_files_sync, m)?)?;
    m.add_function(wrap_pyfunction!(batch_extract_bytes_sync, m)?)?;
    m.add_function(wrap_pyfunction!(batch_extract_files, m)?)?;
    m.add_function(wrap_pyfunction!(batch_extract_bytes, m)?)?;
    m.add_function(wrap_pyfunction!(detect_mime_type_from_bytes, m)?)?;
    m.add_function(wrap_pyfunction!(get_extensions_for_mime, m)?)?;
    m.add_function(wrap_pyfunction!(clear_embedding_backends, m)?)?;
    m.add_function(wrap_pyfunction!(list_embedding_backends, m)?)?;
    m.add_function(wrap_pyfunction!(list_document_extractors, m)?)?;
    m.add_function(wrap_pyfunction!(clear_document_extractors, m)?)?;
    m.add_function(wrap_pyfunction!(list_ocr_backends, m)?)?;
    m.add_function(wrap_pyfunction!(clear_ocr_backends, m)?)?;
    m.add_function(wrap_pyfunction!(list_post_processors, m)?)?;
    m.add_function(wrap_pyfunction!(clear_post_processors, m)?)?;
    m.add_function(wrap_pyfunction!(list_renderers, m)?)?;
    m.add_function(wrap_pyfunction!(clear_renderers, m)?)?;
    m.add_function(wrap_pyfunction!(list_validators, m)?)?;
    m.add_function(wrap_pyfunction!(clear_validators, m)?)?;
    m.add_function(wrap_pyfunction!(compare, m)?)?;
    m.add_function(wrap_pyfunction!(embed_texts_async, m)?)?;
    m.add_function(wrap_pyfunction!(render_pdf_page_to_png, m)?)?;
    m.add_function(wrap_pyfunction!(detect_mime_type, m)?)?;
    m.add_function(wrap_pyfunction!(embed_texts, m)?)?;
    m.add_function(wrap_pyfunction!(get_embedding_preset, m)?)?;
    m.add_function(wrap_pyfunction!(list_embedding_presets, m)?)?;
    m.add_function(wrap_pyfunction!(register_ocr_backend, m)?)?;
    m.add_function(wrap_pyfunction!(register_post_processor, m)?)?;
    m.add_function(wrap_pyfunction!(register_validator, m)?)?;
    m.add_function(wrap_pyfunction!(register_embedding_backend, m)?)?;
    m.add_function(wrap_pyfunction!(register_document_extractor, m)?)?;
    m.add_function(wrap_pyfunction!(register_renderer, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_unregister_ocr_backend, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_unregister_post_processor, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_unregister_validator, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_unregister_embedding_backend, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_unregister_document_extractor, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_unregister_renderer, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_clear_ocr_backends, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_clear_post_processors, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_clear_validators, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_clear_embedding_backends, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_clear_document_extractors, m)?)?;
    m.add_function(wrap_pyfunction!(_alef_clear_renderers, m)?)?;
    m.add("IoError", m.py().get_type::<IoError>())?;
    m.add("ParsingError", m.py().get_type::<ParsingError>())?;
    m.add("OcrError", m.py().get_type::<OcrError>())?;
    m.add("ValidationError", m.py().get_type::<ValidationError>())?;
    m.add("CacheError", m.py().get_type::<CacheError>())?;
    m.add("ImageProcessingError", m.py().get_type::<ImageProcessingError>())?;
    m.add("SerializationError", m.py().get_type::<SerializationError>())?;
    m.add("MissingDependencyError", m.py().get_type::<MissingDependencyError>())?;
    m.add("PluginError", m.py().get_type::<PluginError>())?;
    m.add("LockPoisonedError", m.py().get_type::<LockPoisonedError>())?;
    m.add("UnsupportedFormatError", m.py().get_type::<UnsupportedFormatError>())?;
    m.add("EmbeddingError", m.py().get_type::<EmbeddingError>())?;
    m.add("KreuzbergTimeoutError", m.py().get_type::<KreuzbergTimeoutError>())?;
    m.add("CancelledError", m.py().get_type::<CancelledError>())?;
    m.add("SecurityError", m.py().get_type::<SecurityError>())?;
    m.add("OtherError", m.py().get_type::<OtherError>())?;
    m.add("KreuzbergError", m.py().get_type::<KreuzbergError>())?;
    Ok(())
}
