// 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>
/// Configuration for security limits across extractors.
///
/// All limits are intentionally conservative to prevent DoS attacks
/// while still supporting legitimate documents.
/// </summary>
public sealed record SecurityLimits
{
    /// <summary>
    /// Maximum uncompressed size for archives (500 MB)
    /// </summary>
    [JsonPropertyName("max_archive_size")]
    public ulong MaxArchiveSize { get; init; } = 524288000;

    /// <summary>
    /// Maximum compression ratio before flagging as potential bomb (100:1)
    /// </summary>
    [JsonPropertyName("max_compression_ratio")]
    public ulong MaxCompressionRatio { get; init; } = 100;

    /// <summary>
    /// Maximum number of files in archive (10,000)
    /// </summary>
    [JsonPropertyName("max_files_in_archive")]
    public ulong MaxFilesInArchive { get; init; } = 10000;

    /// <summary>
    /// Maximum nesting depth for structures (100)
    /// </summary>
    [JsonPropertyName("max_nesting_depth")]
    public ulong MaxNestingDepth { get; init; } = 1024;

    /// <summary>
    /// Maximum length of any single XML entity / attribute / token (1 MiB).
    /// This is a per-token cap, NOT a total cap — billion-laughs class
    /// attacks where a single entity expands to hundreds of MB are caught
    /// here, while normal long text content (a paragraph, a CDATA block) is
    /// caught by `max_content_size` instead.
    /// </summary>
    [JsonPropertyName("max_entity_length")]
    public ulong MaxEntityLength { get; init; } = 1048576;

    /// <summary>
    /// Maximum string growth per document (100 MB)
    /// </summary>
    [JsonPropertyName("max_content_size")]
    public ulong MaxContentSize { get; init; } = 104857600;

    /// <summary>
    /// Maximum iterations per operation
    /// </summary>
    [JsonPropertyName("max_iterations")]
    public ulong MaxIterations { get; init; } = 10000000;

    /// <summary>
    /// Maximum XML depth (100 levels)
    /// </summary>
    [JsonPropertyName("max_xml_depth")]
    public ulong MaxXmlDepth { get; init; } = 1024;

    /// <summary>
    /// Maximum cells per table (100,000)
    /// </summary>
    [JsonPropertyName("max_table_cells")]
    public ulong MaxTableCells { get; init; } = 100000;


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