// 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>
/// Bounding geometry for an OCR element.
///
/// Supports both axis-aligned rectangles (from Tesseract) and 4-point quadrilaterals
/// (from PaddleOCR and rotated text detection).
/// </summary>
    [JsonConverter(typeof(OcrBoundingGeometryJsonConverter))]
public abstract record OcrBoundingGeometry
{
    /// <summary>
    /// Axis-aligned bounding box (typical for Tesseract output).
    /// </summary>
    public sealed record Rectangle(
        [property: JsonPropertyName("left")] uint Left,
        [property: JsonPropertyName("top")] uint Top,
        [property: JsonPropertyName("width")] uint Width,
        [property: JsonPropertyName("height")] uint Height
    ) : OcrBoundingGeometry;

    /// <summary>
    /// 4-point quadrilateral for rotated/skewed text (PaddleOCR).
    ///
    /// Points are in clockwise order starting from top-left:
    /// `[top_left, top_right, bottom_right, bottom_left]`
    /// </summary>
    public sealed record Quadrilateral(
        [property: JsonPropertyName("points")] string Points
    ) : OcrBoundingGeometry;

}

/// <summary>
/// Custom converter for OcrBoundingGeometry 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 OcrBoundingGeometryJsonConverter : JsonConverter<OcrBoundingGeometry>
{
    public override OcrBoundingGeometry 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
        {            "rectangle" => JsonSerializer.Deserialize<OcrBoundingGeometry.Rectangle>(flatJson, options) ?? throw new JsonException("Failed to deserialize variant"),            "quadrilateral" => JsonSerializer.Deserialize<OcrBoundingGeometry.Quadrilateral>(flatJson, options) ?? throw new JsonException("Failed to deserialize variant"),            _ => throw new JsonException($"Unknown OcrBoundingGeometry discriminator: {tagValue}")
        };
    }

    public override void Write(Utf8JsonWriter writer, OcrBoundingGeometry 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 OcrBoundingGeometry.Rectangle v_rectangle:
                tag = "rectangle";                inner = v_rectangle;                break;            case OcrBoundingGeometry.Quadrilateral v_quadrilateral:
                tag = "quadrilateral";                inner = v_quadrilateral;                break;            default:
                throw new JsonException($"Unknown OcrBoundingGeometry 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();
    }
}
