// <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.RealtimeConversation
{
    internal partial class InternalRealtimeResponse : IJsonModel<InternalRealtimeResponse>
    {
        internal InternalRealtimeResponse()
        {
        }

        void IJsonModel<InternalRealtimeResponse>.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<InternalRealtimeResponse>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(InternalRealtimeResponse)} does not support writing '{format}' format.");
            }
            if (Optional.IsDefined(Id) && _additionalBinaryDataProperties?.ContainsKey("id") != true)
            {
                writer.WritePropertyName("id"u8);
                writer.WriteStringValue(Id);
            }
            if (Optional.IsDefined(Object) && _additionalBinaryDataProperties?.ContainsKey("object") != true)
            {
                writer.WritePropertyName("object"u8);
                writer.WriteStringValue(Object.Value.ToString());
            }
            if (Optional.IsDefined(Status) && _additionalBinaryDataProperties?.ContainsKey("status") != true)
            {
                writer.WritePropertyName("status"u8);
                writer.WriteStringValue(Status.Value.ToString());
            }
            if (Optional.IsDefined(StatusDetails) && _additionalBinaryDataProperties?.ContainsKey("status_details") != true)
            {
                writer.WritePropertyName("status_details"u8);
                writer.WriteObjectValue(StatusDetails, options);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("metadata") != true)
            {
                if (Metadata != null && 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 (Optional.IsDefined(Usage) && _additionalBinaryDataProperties?.ContainsKey("usage") != true)
            {
                writer.WritePropertyName("usage"u8);
                writer.WriteObjectValue(Usage, options);
            }
            if (Optional.IsDefined(ConversationId) && _additionalBinaryDataProperties?.ContainsKey("conversation_id") != true)
            {
                writer.WritePropertyName("conversation_id"u8);
                writer.WriteStringValue(ConversationId);
            }
            if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true)
            {
                writer.WritePropertyName("temperature"u8);
                writer.WriteNumberValue(Temperature.Value);
            }
            if (Optional.IsDefined(MaxOutputTokens) && _additionalBinaryDataProperties?.ContainsKey("max_output_tokens") != true)
            {
                writer.WritePropertyName("max_output_tokens"u8);
#if NET6_0_OR_GREATER
                writer.WriteRawValue(MaxOutputTokens);
#else
                using (JsonDocument document = JsonDocument.Parse(MaxOutputTokens))
                {
                    JsonSerializer.Serialize(writer, document.RootElement);
                }
#endif
            }
            if (Optional.IsCollectionDefined(Output) && _additionalBinaryDataProperties?.ContainsKey("output") != true)
            {
                writer.WritePropertyName("output"u8);
                writer.WriteStartArray();
                foreach (ConversationItem item in Output)
                {
                    writer.WriteObjectValue(item, options);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsCollectionDefined(Modalities) && _additionalBinaryDataProperties?.ContainsKey("modalities") != true)
            {
                writer.WritePropertyName("modalities"u8);
                writer.WriteStartArray();
                foreach (InternalRealtimeResponseModality item in Modalities)
                {
                    writer.WriteStringValue(item.ToString());
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(Voice) && _additionalBinaryDataProperties?.ContainsKey("voice") != true)
            {
                writer.WritePropertyName("voice"u8);
                writer.WriteStringValue(Voice.Value.ToString());
            }
            if (Optional.IsDefined(OutputAudioFormat) && _additionalBinaryDataProperties?.ContainsKey("output_audio_format") != true)
            {
                writer.WritePropertyName("output_audio_format"u8);
                writer.WriteStringValue(OutputAudioFormat.Value.ToString());
            }
            if (true && _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
                }
            }
        }

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

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

        internal static InternalRealtimeResponse DeserializeInternalRealtimeResponse(JsonElement element, ModelReaderWriterOptions options)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return null;
            }
            string id = default;
            InternalRealtimeResponseObject? @object = default;
            ConversationStatus? status = default;
            ConversationStatusDetails statusDetails = default;
            IDictionary<string, string> metadata = default;
            ConversationTokenUsage usage = default;
            string conversationId = default;
            float? temperature = default;
            BinaryData maxOutputTokens = default;
            IReadOnlyList<ConversationItem> output = default;
            IReadOnlyList<InternalRealtimeResponseModality> modalities = default;
            ConversationVoice? voice = default;
            ConversationAudioFormat? outputAudioFormat = default;
            IDictionary<string, BinaryData> additionalBinaryDataProperties = new ChangeTrackingDictionary<string, BinaryData>();
            foreach (var prop in element.EnumerateObject())
            {
                if (prop.NameEquals("id"u8))
                {
                    id = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("object"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    @object = new InternalRealtimeResponseObject(prop.Value.GetString());
                    continue;
                }
                if (prop.NameEquals("status"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    status = new ConversationStatus(prop.Value.GetString());
                    continue;
                }
                if (prop.NameEquals("status_details"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    statusDetails = ConversationStatusDetails.DeserializeConversationStatusDetails(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("usage"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    usage = ConversationTokenUsage.DeserializeConversationTokenUsage(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("conversation_id"u8))
                {
                    conversationId = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("temperature"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    temperature = prop.Value.GetSingle();
                    continue;
                }
                if (prop.NameEquals("max_output_tokens"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    maxOutputTokens = BinaryData.FromString(prop.Value.GetRawText());
                    continue;
                }
                if (prop.NameEquals("output"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<ConversationItem> array = new List<ConversationItem>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(ConversationItem.DeserializeConversationItem(item, options));
                    }
                    output = array;
                    continue;
                }
                if (prop.NameEquals("modalities"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<InternalRealtimeResponseModality> array = new List<InternalRealtimeResponseModality>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(new InternalRealtimeResponseModality(item.GetString()));
                    }
                    modalities = array;
                    continue;
                }
                if (prop.NameEquals("voice"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    voice = new ConversationVoice(prop.Value.GetString());
                    continue;
                }
                if (prop.NameEquals("output_audio_format"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    outputAudioFormat = new ConversationAudioFormat(prop.Value.GetString());
                    continue;
                }
                if (true)
                {
                    additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText()));
                }
            }
            return new InternalRealtimeResponse(
                id,
                @object,
                status,
                statusDetails,
                metadata,
                usage,
                conversationId,
                temperature,
                maxOutputTokens,
                output ?? new ChangeTrackingList<ConversationItem>(),
                modalities ?? new ChangeTrackingList<InternalRealtimeResponseModality>(),
                voice,
                outputAudioFormat,
                additionalBinaryDataProperties);
        }

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

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

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

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

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

        public static implicit operator BinaryContent(InternalRealtimeResponse internalRealtimeResponse)
        {
            if (internalRealtimeResponse == null)
            {
                return null;
            }
            return BinaryContent.Create(internalRealtimeResponse, ModelSerializationExtensions.WireOptions);
        }

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