// 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>
/// PDF-specific configuration.
/// </summary>
public sealed record PdfConfig
{
    /// <summary>
    /// Extract images from PDF
    /// </summary>
    [JsonPropertyName("extract_images")]
    public bool ExtractImages { get; init; } = false;

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

    /// <summary>
    /// List of passwords to try when opening encrypted PDFs
    /// </summary>
    [JsonPropertyName("passwords")]
    public List<string>? Passwords { get; init; } = null;

    /// <summary>
    /// Extract PDF metadata
    /// </summary>
    [JsonPropertyName("extract_metadata")]
    public bool ExtractMetadata { get; init; } = true;

    /// <summary>
    /// Hierarchy extraction configuration (null = hierarchy extraction disabled)
    /// </summary>
    [JsonPropertyName("hierarchy")]
    public HierarchyConfig? Hierarchy { get; init; } = null;

    /// <summary>
    /// Extract PDF annotations (text notes, highlights, links, stamps).
    /// Default: false
    /// </summary>
    [JsonPropertyName("extract_annotations")]
    public bool ExtractAnnotations { get; init; } = false;

    /// <summary>
    /// Top margin fraction (0.0–1.0) of page height to exclude headers/running heads.
    /// Default: 0.06 (6%)
    /// </summary>
    [JsonPropertyName("top_margin_fraction")]
    public float? TopMarginFraction { get; init; } = null;

    /// <summary>
    /// Bottom margin fraction (0.0–1.0) of page height to exclude footers/page numbers.
    /// Default: 0.05 (5%)
    /// </summary>
    [JsonPropertyName("bottom_margin_fraction")]
    public float? BottomMarginFraction { get; init; } = null;

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

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


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