// 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>
/// Tesseract OCR configuration.
///
/// Provides fine-grained control over Tesseract OCR engine parameters.
/// Most users can use the defaults, but these settings allow optimization
/// for specific document types (invoices, handwriting, etc.).
/// </summary>
public sealed record TesseractConfig
{
    /// <summary>
    /// Language code (e.g., "eng", "deu", "fra")
    /// </summary>
    [JsonPropertyName("language")]
    public string Language { get; init; } = "eng";

    /// <summary>
    /// 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
    /// </summary>
    [JsonPropertyName("psm")]
    public int Psm { get; init; } = 3;

    /// <summary>
    /// Output format ("text" or "markdown")
    /// </summary>
    [JsonPropertyName("output_format")]
    public string OutputFormat { get; init; } = "markdown";

    /// <summary>
    /// 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)
    /// </summary>
    [JsonPropertyName("oem")]
    public int Oem { get; init; } = 3;

    /// <summary>
    /// Minimum confidence threshold (0.0-100.0).
    ///
    /// Words with confidence below this threshold may be rejected or flagged.
    /// </summary>
    [JsonPropertyName("min_confidence")]
    public double MinConfidence { get; init; } = 0.0;

    /// <summary>
    /// Image preprocessing configuration.
    ///
    /// Controls how images are preprocessed before OCR. Can significantly
    /// improve quality for scanned documents or low-quality images.
    /// </summary>
    [JsonPropertyName("preprocessing")]
    public ImagePreprocessingConfig? Preprocessing { get; init; } = null;

    /// <summary>
    /// Enable automatic table detection and reconstruction
    /// </summary>
    [JsonPropertyName("enable_table_detection")]
    public bool EnableTableDetection { get; init; } = true;

    /// <summary>
    /// Minimum confidence threshold for table detection (0.0-1.0)
    /// </summary>
    [JsonPropertyName("table_min_confidence")]
    public double TableMinConfidence { get; init; } = 0.0;

    /// <summary>
    /// Column threshold for table detection (pixels)
    /// </summary>
    [JsonPropertyName("table_column_threshold")]
    public int TableColumnThreshold { get; init; } = 50;

    /// <summary>
    /// Row threshold ratio for table detection (0.0-1.0)
    /// </summary>
    [JsonPropertyName("table_row_threshold_ratio")]
    public double TableRowThresholdRatio { get; init; } = 0.5;

    /// <summary>
    /// Enable OCR result caching
    /// </summary>
    [JsonPropertyName("use_cache")]
    public bool UseCache { get; init; } = true;

    /// <summary>
    /// Use pre-adapted templates for character classification
    /// </summary>
    [JsonPropertyName("classify_use_pre_adapted_templates")]
    public bool ClassifyUsePreAdaptedTemplates { get; init; } = true;

    /// <summary>
    /// Enable N-gram language model
    /// </summary>
    [JsonPropertyName("language_model_ngram_on")]
    public bool LanguageModelNgramOn { get; init; } = false;

    /// <summary>
    /// Don't reject good words during block-level processing
    /// </summary>
    [JsonPropertyName("tessedit_dont_blkrej_good_wds")]
    public bool TesseditDontBlkrejGoodWds { get; init; } = true;

    /// <summary>
    /// Don't reject good words during row-level processing
    /// </summary>
    [JsonPropertyName("tessedit_dont_rowrej_good_wds")]
    public bool TesseditDontRowrejGoodWds { get; init; } = true;

    /// <summary>
    /// Enable dictionary correction
    /// </summary>
    [JsonPropertyName("tessedit_enable_dict_correction")]
    public bool TesseditEnableDictCorrection { get; init; } = true;

    /// <summary>
    /// Whitelist of allowed characters (empty = all allowed)
    /// </summary>
    [JsonPropertyName("tessedit_char_whitelist")]
    public string TesseditCharWhitelist { get; init; } = "";

    /// <summary>
    /// Blacklist of forbidden characters (empty = none forbidden)
    /// </summary>
    [JsonPropertyName("tessedit_char_blacklist")]
    public string TesseditCharBlacklist { get; init; } = "";

    /// <summary>
    /// Use primary language params model
    /// </summary>
    [JsonPropertyName("tessedit_use_primary_params_model")]
    public bool TesseditUsePrimaryParamsModel { get; init; } = true;

    /// <summary>
    /// Variable-width space detection
    /// </summary>
    [JsonPropertyName("textord_space_size_is_variable")]
    public bool TextordSpaceSizeIsVariable { get; init; } = true;

    /// <summary>
    /// Use adaptive thresholding method
    /// </summary>
    [JsonPropertyName("thresholding_method")]
    public bool ThresholdingMethod { get; init; } = false;


    /// <summary>
    /// Parse a <see cref="TesseractConfig"/> from a JSON string.
    /// </summary>
    /// <exception cref="KreuzbergException">When the JSON cannot be deserialised.</exception>
    public static TesseractConfig FromJson(string json)
    {
        try
        {
            return JsonSerializer.Deserialize<TesseractConfig>(json, JsonOptions)
                ?? throw new KreuzbergException($"Failed to parse TesseractConfig from JSON: deserializer returned null");
        }
        catch (KreuzbergException)
        {
            throw;
        }
        catch (Exception e)
        {
            throw new KreuzbergException($"Failed to parse TesseractConfig 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 TesseractConfig Default()
    {
        var nativeResult = NativeMethods.TesseractConfigDefault();
        var jsonPtr = NativeMethods.TesseractConfigToJson(nativeResult);
        var json = global::System.Runtime.InteropServices.Marshal.PtrToStringUTF8(jsonPtr);
        NativeMethods.FreeString(jsonPtr);
        NativeMethods.TesseractConfigFree(nativeResult);
        return JsonSerializer.Deserialize<TesseractConfig>(json ?? "null", JsonOptions)!;
    }
}
