// 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>
/// Embedding configuration for text chunks.
///
/// Configures embedding generation using ONNX models via the vendored embedding engine.
/// Requires the `embeddings` feature to be enabled.
/// </summary>
public sealed record EmbeddingConfig
{
    /// <summary>
    /// The embedding model to use (defaults to "balanced" preset if not specified)
    /// </summary>
    [JsonPropertyName("model")]
    public EmbeddingModelType? Model { get; init; } = null;

    /// <summary>
    /// Whether to normalize embedding vectors (recommended for cosine similarity)
    /// </summary>
    [JsonPropertyName("normalize")]
    public bool Normalize { get; init; } = true;

    /// <summary>
    /// Batch size for embedding generation
    /// </summary>
    [JsonPropertyName("batch_size")]
    public ulong BatchSize { get; init; } = 32;

    /// <summary>
    /// Show model download progress
    /// </summary>
    [JsonPropertyName("show_download_progress")]
    public bool ShowDownloadProgress { get; init; } = false;

    /// <summary>
    /// Custom cache directory for model files
    ///
    /// Defaults to `~/.cache/kreuzberg/embeddings/` if not specified.
    /// Allows full customization of model download location.
    /// </summary>
    [JsonPropertyName("cache_dir")]
    public string? CacheDir { get; init; } = null;

    /// <summary>
    /// Hardware acceleration for the embedding ONNX model.
    ///
    /// When set, controls which execution provider (CPU, CUDA, CoreML, TensorRT)
    /// is used for inference. Defaults to `None` (auto-select per platform).
    /// </summary>
    [JsonPropertyName("acceleration")]
    public AccelerationConfig? Acceleration { get; init; } = null;

    /// <summary>
    /// Maximum wall-clock duration (in seconds) for a single `embed()` call when
    /// using `EmbeddingModelType.Plugin`.
    ///
    /// Applies only to the in-process plugin path — protects against hung
    /// host-language backends (e.g. a Python callback deadlocked on the GIL,
    /// a model stuck on CUDA OOM retries, etc.). On timeout, the dispatcher
    /// returns `Plugin` instead of blocking forever.
    ///
    /// `None` disables the timeout. The default (60 seconds) is conservative
    /// for common in-process inference; increase for large batches on slow
    /// hardware.
    /// </summary>
    [JsonPropertyName("max_embed_duration_secs")]
    public ulong? MaxEmbedDurationSecs { get; init; } = null;


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