// 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>
/// Chunking configuration.
///
/// Configures text chunking for document content, including chunk size,
/// overlap, trimming behavior, and optional embeddings.
///
/// Use `..Default.default()` when constructing to allow for future field additions:
/// </summary>
public sealed record ChunkingConfig
{
    /// <summary>
    /// 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
    /// </summary>
    [JsonPropertyName("max_chars")]
    public ulong MaxCharacters { get; init; } = 1000;

    /// <summary>
    /// Overlap between chunks (in units determined by `sizing`).
    ///
    /// Default: 200
    /// </summary>
    [JsonPropertyName("max_overlap")]
    public ulong Overlap { get; init; } = 200;

    /// <summary>
    /// Whether to trim whitespace from chunk boundaries.
    ///
    /// Default: true
    /// </summary>
    [JsonPropertyName("trim")]
    public bool Trim { get; init; } = true;

    /// <summary>
    /// Type of chunker to use (Text or Markdown).
    ///
    /// Default: Text
    /// </summary>
    [JsonPropertyName("chunker_type")]
    public ChunkerType ChunkerType { get; init; } = ChunkerType.Text;

    /// <summary>
    /// Optional embedding configuration for chunk embeddings.
    /// </summary>
    [JsonPropertyName("embedding")]
    public EmbeddingConfig? Embedding { get; init; } = null;

    /// <summary>
    /// Use a preset configuration (overrides individual settings if provided).
    /// </summary>
    [JsonPropertyName("preset")]
    public string? Preset { get; init; } = null;

    /// <summary>
    /// How to measure chunk size.
    ///
    /// Default: `Characters` (Unicode character count).
    /// Enable `chunking-tiktoken` or `chunking-tokenizers` features for token-based sizing.
    /// </summary>
    [JsonPropertyName("sizing")]
    public ChunkSizing? Sizing { get; init; } = null;

    /// <summary>
    /// When `true` and `chunker_type` is `Markdown`, prepend the heading hierarchy
    /// path (e.g. `"# Title &gt; ## 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`
    /// </summary>
    [JsonPropertyName("prepend_heading_context")]
    public bool PrependHeadingContext { get; init; } = false;

    /// <summary>
    /// 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`.
    /// </summary>
    [JsonPropertyName("topic_threshold")]
    public float? TopicThreshold { get; init; } = null;


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