// This file is auto-generated by alef — DO NOT EDIT.
// alef:hash:4e15143f4af1ae8bafbdb1506ef057da924484c66a19483966333558ad437e75
// To regenerate: alef generate
// To verify freshness: alef verify --exit-code
// Issues & docs: https://github.com/kreuzberg-dev/alef
#nullable enable

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Kreuzberg;

/// <summary>
/// OCR configuration.
/// </summary>
public sealed record OcrConfig
{
    /// <summary>
    /// 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.
    /// </summary>
    [JsonPropertyName("enabled")]
    public bool Enabled { get; init; } = true;

    /// <summary>
    /// OCR backend: tesseract, easyocr, paddleocr
    /// </summary>
    [JsonPropertyName("backend")]
    public string Backend { get; init; } = "";

    /// <summary>
    /// Language code (e.g., "eng", "deu")
    /// </summary>
    [JsonPropertyName("language")]
    public string Language { get; init; } = "";

    /// <summary>
    /// Tesseract-specific configuration (optional)
    /// </summary>
    [JsonPropertyName("tesseract_config")]
    public TesseractConfig? TesseractConfig { get; init; } = null;

    /// <summary>
    /// Output format for OCR results (optional, for format conversion)
    /// </summary>
    [JsonPropertyName("output_format")]
    public OutputFormat? OutputFormat { get; init; } = null;

    /// <summary>
    /// PaddleOCR-specific configuration (optional, JSON passthrough)
    /// </summary>
    [JsonPropertyName("paddle_ocr_config")]
    public string? PaddleOcrConfig { get; init; } = null;

    /// <summary>
    /// 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 }
    /// ```
    /// </summary>
    [JsonPropertyName("backend_options")]
    public string? BackendOptions { get; init; } = null;

    /// <summary>
    /// OCR element extraction configuration
    /// </summary>
    [JsonPropertyName("element_config")]
    public OcrElementConfig? ElementConfig { get; init; } = null;

    /// <summary>
    /// Quality thresholds for the native-text-to-OCR fallback decision.
    /// When null, uses compiled defaults (matching previous hardcoded behavior).
    /// </summary>
    [JsonPropertyName("quality_thresholds")]
    public OcrQualityThresholds? QualityThresholds { get; init; } = null;

    /// <summary>
    /// Multi-backend OCR pipeline configuration. When set, enables weighted
    /// fallback across multiple OCR backends based on output quality.
    /// When null, uses the single `backend` field (same as today).
    /// </summary>
    [JsonPropertyName("pipeline")]
    public OcrPipelineConfig? Pipeline { get; init; } = null;

    /// <summary>
    /// 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.
    /// </summary>
    [JsonPropertyName("auto_rotate")]
    public bool AutoRotate { get; init; } = false;

    /// <summary>
    /// 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.
    /// </summary>
    [JsonPropertyName("vlm_config")]
    public LlmConfig? VlmConfig { get; init; } = null;

    /// <summary>
    /// Custom Jinja2 prompt template for VLM OCR.
    ///
    /// When `None`, uses the default template. Available variables:
    /// - `{{ language }}` — The document language code (e.g., "eng", "deu").
    /// </summary>
    [JsonPropertyName("vlm_prompt")]
    public string? VlmPrompt { get; init; } = null;

    /// <summary>
    /// 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.
    /// </summary>
    [JsonPropertyName("acceleration")]
    public AccelerationConfig? Acceleration { get; init; } = null;

    /// <summary>
    /// 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.
    /// </summary>
    [JsonPropertyName("tessdata_bytes")]
    public Dictionary<string, byte[]>? TessdataBytes { get; init; } = null;


    /// <summary>
    /// Parse a <see cref="OcrConfig"/> from a JSON string.
    /// </summary>
    /// <exception cref="KreuzbergException">When the JSON cannot be deserialised.</exception>
    public static OcrConfig FromJson(string json)
    {
        try
        {
            return JsonSerializer.Deserialize<OcrConfig>(json, JsonOptions)
                ?? throw new KreuzbergException($"Failed to parse OcrConfig from JSON: deserializer returned null");
        }
        catch (KreuzbergException)
        {
            throw;
        }
        catch (Exception e)
        {
            throw new KreuzbergException($"Failed to parse OcrConfig from JSON: {e.Message}", e);
        }
    }

    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) },
    };

    /// <summary>Options for serializing config/input objects to FFI. Strips nulls
    /// (nullable C# fields default to null and would override required Rust fields with
    /// non-deserialisable nulls) but preserves explicit false/0 so caller intent is kept.</summary>
    private static readonly JsonSerializerOptions JsonSerializationOptions = new()
    {
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) },
    };

    public static OcrConfig Default()
    {
        var nativeResult = NativeMethods.OcrConfigDefault();
        var jsonPtr = NativeMethods.OcrConfigToJson(nativeResult);
        var json = global::System.Runtime.InteropServices.Marshal.PtrToStringUTF8(jsonPtr);
        NativeMethods.FreeString(jsonPtr);
        NativeMethods.OcrConfigFree(nativeResult);
        return JsonSerializer.Deserialize<OcrConfig>(json ?? "null", JsonOptions)!;
    }
}
