// 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>
/// Embedding model types supported by Kreuzberg.
/// </summary>
    [JsonConverter(typeof(EmbeddingModelTypeJsonConverter))]
public abstract record EmbeddingModelType
{
    /// <summary>
    /// Use a preset model configuration (recommended)
    /// </summary>
    public sealed record Preset(
        [property: JsonPropertyName("name")] string Name
    ) : EmbeddingModelType;

    /// <summary>
    /// Use a custom ONNX model from HuggingFace
    /// </summary>
    public sealed record Custom(
        [property: JsonPropertyName("model_id")] string ModelId,
        [property: JsonPropertyName("dimensions")] ulong Dimensions
    ) : EmbeddingModelType;

    /// <summary>
    /// Provider-hosted embedding model via liter-llm.
    ///
    /// Uses the model specified in the nested `LlmConfig` (e.g.,
    /// `"openai/text-embedding-3-small"`).
    /// </summary>
    public sealed record Llm(
        [property: JsonPropertyName("llm")] LlmConfig Value
    ) : EmbeddingModelType;

    /// <summary>
    /// In-process embedding backend registered via the plugin system.
    ///
    /// The caller registers an `EmbeddingBackend`(crate.plugins.EmbeddingBackend) once
    /// (e.g. a wrapper around an already-loaded `llama-cpp-python`, `sentence-transformers`,
    /// or tuned ONNX model), then references it by name in config. Kreuzberg calls back
    /// into the registered backend during chunking and standalone embed requests —
    /// no HuggingFace download, no ONNX Runtime requirement, no HTTP sidecar.
    ///
    /// When this variant is selected, only the following `EmbeddingConfig` fields
    /// apply: `normalize` (post-call L2 normalization) and `max_embed_duration_secs`
    /// (dispatcher timeout). Model-loading fields (`batch_size`, `cache_dir`,
    /// `show_download_progress`, `acceleration`) are ignored — the host owns the
    /// model lifecycle.
    ///
    /// Semantic chunking falls back to `ChunkingConfig.max_characters` when this variant
    /// is used, since there is no preset to look a chunk-size ceiling up against — size your
    /// context window via `max_characters` directly.
    ///
    /// See `register_embedding_backend`.
    /// </summary>
    public sealed record Plugin(
        [property: JsonPropertyName("name")] string Name
    ) : EmbeddingModelType;

}

/// <summary>
/// Custom converter for EmbeddingModelType 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 EmbeddingModelTypeJsonConverter : JsonConverter<EmbeddingModelType>
{
    public override EmbeddingModelType 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
        {            "preset" => JsonSerializer.Deserialize<EmbeddingModelType.Preset>(flatJson, options) ?? throw new JsonException("Failed to deserialize variant"),            "custom" => JsonSerializer.Deserialize<EmbeddingModelType.Custom>(flatJson, options) ?? throw new JsonException("Failed to deserialize variant"),            "llm" => JsonSerializer.Deserialize<EmbeddingModelType.Llm>(flatJson, options) ?? throw new JsonException("Failed to deserialize variant"),            "plugin" => JsonSerializer.Deserialize<EmbeddingModelType.Plugin>(flatJson, options) ?? throw new JsonException("Failed to deserialize variant"),            _ => throw new JsonException($"Unknown EmbeddingModelType discriminator: {tagValue}")
        };
    }

    public override void Write(Utf8JsonWriter writer, EmbeddingModelType 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 EmbeddingModelType.Preset v_preset:
                tag = "preset";                inner = v_preset;                break;            case EmbeddingModelType.Custom v_custom:
                tag = "custom";                inner = v_custom;                break;            case EmbeddingModelType.Llm v_llm:
                tag = "llm";                inner = v_llm;                break;            case EmbeddingModelType.Plugin v_plugin:
                tag = "plugin";                inner = v_plugin;                break;            default:
                throw new JsonException($"Unknown EmbeddingModelType 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();
    }
}
