// 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.IO;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Kreuzberg;

/// <summary>
/// Best-effort document location for a revision.
/// </summary>
    [JsonConverter(typeof(RevisionAnchorJsonConverter))]
public abstract record RevisionAnchor
{
    /// <summary>
    /// Body paragraph, identified by its zero-based index in the document flow.
    /// </summary>
    public sealed record Paragraph(
        [property: JsonPropertyName("index")] ulong Index
    ) : RevisionAnchor;

    /// <summary>
    /// Cell inside a table.
    /// </summary>
    public sealed record TableCell(
        [property: JsonPropertyName("row")] ulong Row,
        [property: JsonPropertyName("col")] ulong Col,
        [property: JsonPropertyName("table_index")] ulong TableIndex
    ) : RevisionAnchor;

    /// <summary>
    /// Page, identified by its zero-based index.
    /// </summary>
    public sealed record Page(
        [property: JsonPropertyName("index")] ulong Index
    ) : RevisionAnchor;

    /// <summary>
    /// Presentation slide, identified by its zero-based index.
    /// </summary>
    public sealed record Slide(
        [property: JsonPropertyName("index")] ulong Index
    ) : RevisionAnchor;

    /// <summary>
    /// Spreadsheet cell or range, identified by sheet index and optional name.
    /// </summary>
    public sealed record Sheet(
        [property: JsonPropertyName("index")] ulong Index,
        [property: JsonPropertyName("name")] string? Name
    ) : RevisionAnchor;

}

/// <summary>
/// Custom converter for RevisionAnchor sealed union with flattened variant fields.
/// </summary>
/// <remarks>
/// Handles JSON objects with a discriminator field (type) and variant-specific
/// fields at the same level. System.Text.Json's [JsonPolymorphic] cannot handle
/// this layout, so we manually deserialize here.
/// </remarks>
public sealed class RevisionAnchorJsonConverter : JsonConverter<RevisionAnchor>
{
    public override RevisionAnchor Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType != JsonTokenType.StartObject)
        {
            throw new JsonException($"Expected JSON object, got {reader.TokenType}");
        }

        using var doc = JsonDocument.ParseValue(ref reader);
        var root = doc.RootElement;

        if (!root.TryGetProperty("type", out var tagElement))
        {
            throw new JsonException($"Missing discriminator field: type");
        }

        var tagValue = tagElement.GetString();
        if (tagValue == null)
        {
            throw new JsonException("Discriminator field is null");
        }

        // Tuple-variant records (`Variant(InnerStruct value)`) expect a single
        // "Value" field holding the inner struct's JSON, so wrap the remaining
        // fields under "Value". Struct-variant records (`Variant { field1,
        // field2 }`) have positional record components annotated with
        // [JsonPropertyName(...)] for each named field, so pass the remaining
        // fields through directly without the wrap.
        using var ms = new MemoryStream();
        using var writer = new Utf8JsonWriter(ms);
        writer.WriteStartObject();
        foreach (var prop in root.EnumerateObject())
        {
            if (prop.Name != "type")
            {
                writer.WritePropertyName(prop.Name);
                prop.Value.WriteTo(writer);
            }
        }
        writer.WriteEndObject();
        writer.Flush();
        ms.Position = 0;
        var flatJson = ms.ToArray();

        using var msWrapped = new MemoryStream();
        using var writerWrapped = new Utf8JsonWriter(msWrapped);
        writerWrapped.WriteStartObject();
        writerWrapped.WritePropertyName("Value");
        writerWrapped.WriteStartObject();
        foreach (var prop in root.EnumerateObject())
        {
            if (prop.Name != "type")
            {
                writerWrapped.WritePropertyName(prop.Name);
                prop.Value.WriteTo(writerWrapped);
            }
        }
        writerWrapped.WriteEndObject();
        writerWrapped.WriteEndObject();
        writerWrapped.Flush();
        msWrapped.Position = 0;
        var wrappedJson = msWrapped.ToArray();

        return tagValue switch
        {            "paragraph" => JsonSerializer.Deserialize<RevisionAnchor.Paragraph>(flatJson, options) ?? throw new JsonException("Failed to deserialize variant"),            "table_cell" => JsonSerializer.Deserialize<RevisionAnchor.TableCell>(flatJson, options) ?? throw new JsonException("Failed to deserialize variant"),            "page" => JsonSerializer.Deserialize<RevisionAnchor.Page>(flatJson, options) ?? throw new JsonException("Failed to deserialize variant"),            "slide" => JsonSerializer.Deserialize<RevisionAnchor.Slide>(flatJson, options) ?? throw new JsonException("Failed to deserialize variant"),            "sheet" => JsonSerializer.Deserialize<RevisionAnchor.Sheet>(flatJson, options) ?? throw new JsonException("Failed to deserialize variant"),            _ => throw new JsonException($"Unknown RevisionAnchor discriminator: {tagValue}")
        };
    }

    public override void Write(Utf8JsonWriter writer, RevisionAnchor value, JsonSerializerOptions options)
    {
        // Emit the discriminator tag plus the inner variant's fields flattened at
        // the same level — mirrors the Java sealed-union serializer pattern. Turn
        // `Message.User(UserMessage value)` into `{"type":"user","content":...}`
        // not `{"value":{...}}`. Without this, sending a chat request to FFI fails
        // with "missing field type" inside Rust serde.
        string tag;
        object? inner;
        switch (value)
        {            case RevisionAnchor.Paragraph v_paragraph:
                tag = "paragraph";                inner = v_paragraph;                break;            case RevisionAnchor.TableCell v_tablecell:
                tag = "table_cell";                inner = v_tablecell;                break;            case RevisionAnchor.Page v_page:
                tag = "page";                inner = v_page;                break;            case RevisionAnchor.Slide v_slide:
                tag = "slide";                inner = v_slide;                break;            case RevisionAnchor.Sheet v_sheet:
                tag = "sheet";                inner = v_sheet;                break;            default:
                throw new JsonException($"Unknown RevisionAnchor variant: {value.GetType().Name}");
        }

        writer.WriteStartObject();
        writer.WriteString("type", tag);
        if (inner != null)
        {
            using var doc = JsonSerializer.SerializeToDocument(inner, inner.GetType(), options);
            if (doc.RootElement.ValueKind == JsonValueKind.Object)
            {
                foreach (var prop in doc.RootElement.EnumerateObject())
                {
                    writer.WritePropertyName(prop.Name);
                    prop.Value.WriteTo(writer);
                }
            }
        }
        writer.WriteEndObject();
    }
}
