// 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>
/// Metadata about a chunk's position in the original document.
/// </summary>
public sealed record ChunkMetadata
{
    /// <summary>
    /// Byte offset where this chunk starts in the original text (UTF-8 valid boundary).
    /// </summary>
    [JsonPropertyName("byte_start")]
    public ulong ByteStart { get; init; } = 0;

    /// <summary>
    /// Byte offset where this chunk ends in the original text (UTF-8 valid boundary).
    /// </summary>
    [JsonPropertyName("byte_end")]
    public ulong ByteEnd { get; init; } = 0;

    /// <summary>
    /// Number of tokens in this chunk (if available).
    ///
    /// This is calculated by the embedding model's tokenizer if embeddings are enabled.
    /// </summary>
    [JsonPropertyName("token_count")]
    public ulong? TokenCount { get; init; } = null;

    /// <summary>
    /// Zero-based index of this chunk in the document.
    /// </summary>
    [JsonPropertyName("chunk_index")]
    public ulong ChunkIndex { get; init; } = 0;

    /// <summary>
    /// Total number of chunks in the document.
    /// </summary>
    [JsonPropertyName("total_chunks")]
    public ulong TotalChunks { get; init; } = 0;

    /// <summary>
    /// First page number this chunk spans (1-indexed).
    ///
    /// Only populated when page tracking is enabled in extraction configuration.
    /// </summary>
    [JsonPropertyName("first_page")]
    public uint? FirstPage { get; init; } = null;

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

    /// <summary>
    /// Heading context when using Markdown chunker.
    ///
    /// Contains the heading hierarchy this chunk falls under.
    /// Only populated when `ChunkerType.Markdown` is used.
    /// </summary>
    [JsonPropertyName("heading_context")]
    public HeadingContext? HeadingContext { get; init; } = null;

    /// <summary>
    /// 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.
    /// </summary>
    [JsonPropertyName("image_indices")]
    public List<uint> ImageIndices { get; init; } = [];


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