// 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>
/// Top-level structured document representation.
///
/// A flat array of nodes with index-based parent/child references forming a tree.
/// Root-level nodes have `parent: None`. Use `body_roots()` and `furniture_roots()`
/// to iterate over top-level content by layer.
///
/// # Validation
///
/// Call `validate()` after construction to verify all node indices are in bounds
/// and parent-child relationships are bidirectionally consistent.
/// </summary>
public sealed record DocumentStructure
{
    /// <summary>
    /// All nodes in document/reading order.
    /// </summary>
    [JsonPropertyName("nodes")]
    public List<DocumentNode> Nodes { get; init; } = [];

    /// <summary>
    /// Origin format identifier (e.g. "docx", "pptx", "html", "pdf").
    ///
    /// Allows renderers to apply format-aware heuristics when converting
    /// the document tree to output formats.
    /// </summary>
    [JsonPropertyName("source_format")]
    public string? SourceFormat { get; init; } = null;

    /// <summary>
    /// Resolved relationships between nodes (footnote refs, citations, anchor links, etc.).
    ///
    /// Populated during derivation from the internal document representation.
    /// Empty when no relationships are detected.
    /// </summary>
    [JsonPropertyName("relationships")]
    public List<DocumentRelationship> Relationships { get; init; } = [];

    /// <summary>
    /// Sorted, deduplicated list of node type names present in this document.
    ///
    /// Each value is the snake_case `node_type` tag of the corresponding
    /// `NodeContent` variant (e.g. `"paragraph"`, `"heading"`, `"table"`, …).
    ///
    /// Computed from `nodes` via `DocumentStructure.finalize_node_types`.
    /// Empty until that method is called (internal construction paths call it
    /// at the end of derivation).
    /// </summary>
    [JsonPropertyName("node_types")]
    public List<string> NodeTypes { get; init; } = [];


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