// <auto-generated/>

#nullable disable

using System;
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Collections.Generic;
using System.Text.Json;
using OpenAI;

namespace OpenAI.Evals
{
    internal partial class InternalEvalRun : IJsonModel<InternalEvalRun>
    {
        internal InternalEvalRun() : this(null, null, null, null, null, null, default, null, null, null, null, null, null, null, null)
        {
        }

        void IJsonModel<InternalEvalRun>.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
        {
            writer.WriteStartObject();
            JsonModelWriteCore(writer, options);
            writer.WriteEndObject();
        }

        protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<InternalEvalRun>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(InternalEvalRun)} does not support writing '{format}' format.");
            }
            if (_additionalBinaryDataProperties?.ContainsKey("object") != true)
            {
                writer.WritePropertyName("object"u8);
                writer.WriteStringValue(Object);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("id") != true)
            {
                writer.WritePropertyName("id"u8);
                writer.WriteStringValue(Id);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("eval_id") != true)
            {
                writer.WritePropertyName("eval_id"u8);
                writer.WriteStringValue(EvalId);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("status") != true)
            {
                writer.WritePropertyName("status"u8);
                writer.WriteStringValue(Status);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("model") != true)
            {
                writer.WritePropertyName("model"u8);
                writer.WriteStringValue(Model);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("name") != true)
            {
                writer.WritePropertyName("name"u8);
                writer.WriteStringValue(Name);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true)
            {
                writer.WritePropertyName("created_at"u8);
                writer.WriteNumberValue(CreatedAt, "U");
            }
            if (_additionalBinaryDataProperties?.ContainsKey("report_url") != true)
            {
                writer.WritePropertyName("report_url"u8);
                writer.WriteStringValue(ReportUrl);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("result_counts") != true)
            {
                writer.WritePropertyName("result_counts"u8);
                writer.WriteObjectValue(ResultCounts, options);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("per_model_usage") != true)
            {
                writer.WritePropertyName("per_model_usage"u8);
                writer.WriteStartArray();
                foreach (InternalEvalRunPerModelUsage item in PerModelUsage)
                {
                    writer.WriteObjectValue(item, options);
                }
                writer.WriteEndArray();
            }
            if (_additionalBinaryDataProperties?.ContainsKey("per_testing_criteria_results") != true)
            {
                writer.WritePropertyName("per_testing_criteria_results"u8);
                writer.WriteStartArray();
                foreach (InternalEvalRunPerTestingCriteriaResult item in PerTestingCriteriaResults)
                {
                    writer.WriteObjectValue(item, options);
                }
                writer.WriteEndArray();
            }
            if (_additionalBinaryDataProperties?.ContainsKey("data_source") != true)
            {
                writer.WritePropertyName("data_source"u8);
                writer.WriteObjectValue(DataSource, options);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("metadata") != true)
            {
                if (Optional.IsCollectionDefined(Metadata))
                {
                    writer.WritePropertyName("metadata"u8);
                    writer.WriteStartObject();
                    foreach (var item in Metadata)
                    {
                        writer.WritePropertyName(item.Key);
                        if (item.Value == null)
                        {
                            writer.WriteNullValue();
                            continue;
                        }
                        writer.WriteStringValue(item.Value);
                    }
                    writer.WriteEndObject();
                }
                else
                {
                    writer.WriteNull("metadata"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("error") != true)
            {
                writer.WritePropertyName("error"u8);
                writer.WriteObjectValue(Error, options);
            }
            // Plugin customization: remove options.Format != "W" check
            if (_additionalBinaryDataProperties != null)
            {
                foreach (var item in _additionalBinaryDataProperties)
                {
                    if (ModelSerializationExtensions.IsSentinelValue(item.Value))
                    {
                        continue;
                    }
                    writer.WritePropertyName(item.Key);
#if NET6_0_OR_GREATER
                    writer.WriteRawValue(item.Value);
#else
                    using (JsonDocument document = JsonDocument.Parse(item.Value))
                    {
                        JsonSerializer.Serialize(writer, document.RootElement);
                    }
#endif
                }
            }
        }

        InternalEvalRun IJsonModel<InternalEvalRun>.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => JsonModelCreateCore(ref reader, options);

        protected virtual InternalEvalRun JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<InternalEvalRun>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(InternalEvalRun)} does not support reading '{format}' format.");
            }
            using JsonDocument document = JsonDocument.ParseValue(ref reader);
            return DeserializeInternalEvalRun(document.RootElement, options);
        }

        internal static InternalEvalRun DeserializeInternalEvalRun(JsonElement element, ModelReaderWriterOptions options)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return null;
            }
            string @object = default;
            string id = default;
            string evalId = default;
            string status = default;
            string model = default;
            string name = default;
            DateTimeOffset createdAt = default;
            string reportUrl = default;
            InternalEvalRunResultCounts resultCounts = default;
            IList<InternalEvalRunPerModelUsage> perModelUsage = default;
            IList<InternalEvalRunPerTestingCriteriaResult> perTestingCriteriaResults = default;
            InternalEvalRunDataSourceResource dataSource = default;
            IDictionary<string, string> metadata = default;
            InternalEvalApiError error = default;
            IDictionary<string, BinaryData> additionalBinaryDataProperties = new ChangeTrackingDictionary<string, BinaryData>();
            foreach (var prop in element.EnumerateObject())
            {
                if (prop.NameEquals("object"u8))
                {
                    @object = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("id"u8))
                {
                    id = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("eval_id"u8))
                {
                    evalId = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("status"u8))
                {
                    status = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("model"u8))
                {
                    model = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("name"u8))
                {
                    name = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("created_at"u8))
                {
                    createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("report_url"u8))
                {
                    reportUrl = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("result_counts"u8))
                {
                    resultCounts = InternalEvalRunResultCounts.DeserializeInternalEvalRunResultCounts(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("per_model_usage"u8))
                {
                    List<InternalEvalRunPerModelUsage> array = new List<InternalEvalRunPerModelUsage>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(InternalEvalRunPerModelUsage.DeserializeInternalEvalRunPerModelUsage(item, options));
                    }
                    perModelUsage = array;
                    continue;
                }
                if (prop.NameEquals("per_testing_criteria_results"u8))
                {
                    List<InternalEvalRunPerTestingCriteriaResult> array = new List<InternalEvalRunPerTestingCriteriaResult>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(InternalEvalRunPerTestingCriteriaResult.DeserializeInternalEvalRunPerTestingCriteriaResult(item, options));
                    }
                    perTestingCriteriaResults = array;
                    continue;
                }
                if (prop.NameEquals("data_source"u8))
                {
                    dataSource = InternalEvalRunDataSourceResource.DeserializeInternalEvalRunDataSourceResource(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("metadata"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        metadata = new ChangeTrackingDictionary<string, string>();
                        continue;
                    }
                    Dictionary<string, string> dictionary = new Dictionary<string, string>();
                    foreach (var prop0 in prop.Value.EnumerateObject())
                    {
                        if (prop0.Value.ValueKind == JsonValueKind.Null)
                        {
                            dictionary.Add(prop0.Name, null);
                        }
                        else
                        {
                            dictionary.Add(prop0.Name, prop0.Value.GetString());
                        }
                    }
                    metadata = dictionary;
                    continue;
                }
                if (prop.NameEquals("error"u8))
                {
                    error = InternalEvalApiError.DeserializeInternalEvalApiError(prop.Value, options);
                    continue;
                }
                // Plugin customization: remove options.Format != "W" check
                additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText()));
            }
            return new InternalEvalRun(
                @object,
                id,
                evalId,
                status,
                model,
                name,
                createdAt,
                reportUrl,
                resultCounts,
                perModelUsage,
                perTestingCriteriaResults,
                dataSource,
                metadata,
                error,
                additionalBinaryDataProperties);
        }

        BinaryData IPersistableModel<InternalEvalRun>.Write(ModelReaderWriterOptions options) => PersistableModelWriteCore(options);

        protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<InternalEvalRun>)this).GetFormatFromOptions(options) : options.Format;
            switch (format)
            {
                case "J":
                    return ModelReaderWriter.Write(this, options, OpenAIContext.Default);
                default:
                    throw new FormatException($"The model {nameof(InternalEvalRun)} does not support writing '{options.Format}' format.");
            }
        }

        InternalEvalRun IPersistableModel<InternalEvalRun>.Create(BinaryData data, ModelReaderWriterOptions options) => PersistableModelCreateCore(data, options);

        protected virtual InternalEvalRun PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<InternalEvalRun>)this).GetFormatFromOptions(options) : options.Format;
            switch (format)
            {
                case "J":
                    using (JsonDocument document = JsonDocument.Parse(data))
                    {
                        return DeserializeInternalEvalRun(document.RootElement, options);
                    }
                default:
                    throw new FormatException($"The model {nameof(InternalEvalRun)} does not support reading '{options.Format}' format.");
            }
        }

        string IPersistableModel<InternalEvalRun>.GetFormatFromOptions(ModelReaderWriterOptions options) => "J";

        public static explicit operator InternalEvalRun(ClientResult result)
        {
            using PipelineResponse response = result.GetRawResponse();
            using JsonDocument document = JsonDocument.Parse(response.Content);
            return DeserializeInternalEvalRun(document.RootElement, ModelSerializationExtensions.WireOptions);
        }
    }
}
