// 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>
/// Extraction result metadata.
///
/// Contains common fields applicable to all formats, format-specific metadata
/// via a discriminated union, and additional custom fields from postprocessors.
/// </summary>
public sealed record Metadata
{
    /// <summary>
    /// Document title
    /// </summary>
    [JsonPropertyName("title")]
    public string? Title { get; init; } = null;

    /// <summary>
    /// Document subject or description
    /// </summary>
    [JsonPropertyName("subject")]
    public string? Subject { get; init; } = null;

    /// <summary>
    /// Primary author(s) - always Vec for consistency
    /// </summary>
    [JsonPropertyName("authors")]
    public List<string>? Authors { get; init; } = null;

    /// <summary>
    /// Keywords/tags - always Vec for consistency
    /// </summary>
    [JsonPropertyName("keywords")]
    public List<string>? Keywords { get; init; } = null;

    /// <summary>
    /// Primary language (ISO 639 code)
    /// </summary>
    [JsonPropertyName("language")]
    public string? Language { get; init; } = null;

    /// <summary>
    /// Creation timestamp (ISO 8601 format)
    /// </summary>
    [JsonPropertyName("created_at")]
    public string? CreatedAt { get; init; } = null;

    /// <summary>
    /// Last modification timestamp (ISO 8601 format)
    /// </summary>
    [JsonPropertyName("modified_at")]
    public string? ModifiedAt { get; init; } = null;

    /// <summary>
    /// User who created the document
    /// </summary>
    [JsonPropertyName("created_by")]
    public string? CreatedBy { get; init; } = null;

    /// <summary>
    /// User who last modified the document
    /// </summary>
    [JsonPropertyName("modified_by")]
    public string? ModifiedBy { get; init; } = null;

    /// <summary>
    /// Page/slide/sheet structure with boundaries
    /// </summary>
    [JsonPropertyName("pages")]
    public PageStructure? Pages { get; init; } = null;

    /// <summary>
    /// Format-specific metadata (discriminated union)
    ///
    /// Contains detailed metadata specific to the document format.
    /// Serialized as a nested `"format"` object with a `format_type` discriminator field.
    /// </summary>
    [JsonPropertyName("format")]
    public FormatMetadata? Format { get; init; } = null;

    /// <summary>
    /// Image preprocessing metadata (when OCR preprocessing was applied)
    /// </summary>
    [JsonPropertyName("image_preprocessing")]
    public ImagePreprocessingMetadata? ImagePreprocessing { get; init; } = null;

    /// <summary>
    /// JSON schema (for structured data extraction)
    /// </summary>
    [JsonPropertyName("json_schema")]
    public string? JsonSchema { get; init; } = null;

    /// <summary>
    /// Error metadata (for batch operations)
    /// </summary>
    [JsonPropertyName("error")]
    public ErrorMetadata? Error { get; init; } = null;

    /// <summary>
    /// Extraction duration in milliseconds (for benchmarking).
    ///
    /// This field is populated by batch extraction to provide per-file timing
    /// information. It's `None` for single-file extraction (which uses external timing).
    /// </summary>
    [JsonPropertyName("extraction_duration_ms")]
    public ulong? ExtractionDurationMs { get; init; } = null;

    /// <summary>
    /// Document category (from frontmatter or classification).
    /// </summary>
    [JsonPropertyName("category")]
    public string? Category { get; init; } = null;

    /// <summary>
    /// Document tags (from frontmatter).
    /// </summary>
    [JsonPropertyName("tags")]
    public List<string>? Tags { get; init; } = null;

    /// <summary>
    /// Document version string (from frontmatter).
    /// </summary>
    [JsonPropertyName("document_version")]
    public string? DocumentVersion { get; init; } = null;

    /// <summary>
    /// Abstract or summary text (from frontmatter).
    /// </summary>
    [JsonPropertyName("abstract_text")]
    public string? AbstractText { get; init; } = null;

    /// <summary>
    /// Output format identifier (e.g., "markdown", "html", "text").
    ///
    /// Set by the output format pipeline stage when format conversion is applied.
    /// Previously stored in `metadata.additional["output_format"]`.
    /// </summary>
    [JsonPropertyName("output_format")]
    public string? OutputFormat { get; init; } = null;

    /// <summary>
    /// Whether OCR was used during extraction.
    ///
    /// Set to `true` whenever the extraction pipeline ran an OCR backend
    /// (Tesseract, PaddleOCR, VLM, etc.) and used that output as the primary
    /// or fallback text. `false` means native text extraction was used exclusively.
    /// </summary>
    [JsonPropertyName("ocr_used")]
    public bool OcrUsed { get; init; } = false;

    /// <summary>
    /// Additional custom fields from postprocessors.
    ///
    /// Serialized as a nested `"additional"` object (not flattened at root level).
    /// Uses `Cow&lt;'static, str&gt;` keys so static string keys avoid allocation.
    /// </summary>
    [JsonPropertyName("additional")]
    public Dictionary<string, string> Additional { get; init; } = new Dictionary<string, string>();


    /// <summary>
    /// Parse a <see cref="Metadata"/> from a JSON string.
    /// </summary>
    /// <exception cref="KreuzbergException">When the JSON cannot be deserialised.</exception>
    public static Metadata FromJson(string json)
    {
        try
        {
            return JsonSerializer.Deserialize<Metadata>(json, JsonOptions)
                ?? throw new KreuzbergException($"Failed to parse Metadata from JSON: deserializer returned null");
        }
        catch (KreuzbergException)
        {
            throw;
        }
        catch (Exception e)
        {
            throw new KreuzbergException($"Failed to parse Metadata 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) },
    };
}
