// <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
{
    public partial class ConversationSessionOptions : IJsonModel<ConversationSessionOptions>
    {
        void IJsonModel<ConversationSessionOptions>.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<ConversationSessionOptions>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(ConversationSessionOptions)} does not support writing '{format}' format.");
            }
            if (Optional.IsDefined(Instructions) && _additionalBinaryDataProperties?.ContainsKey("instructions") != true)
            {
                writer.WritePropertyName("instructions"u8);
                writer.WriteStringValue(Instructions);
            }
            if (Optional.IsDefined(Voice) && _additionalBinaryDataProperties?.ContainsKey("voice") != true)
            {
                writer.WritePropertyName("voice"u8);
                writer.WriteStringValue(Voice.Value.ToString());
            }
            if (Optional.IsDefined(InputAudioFormat) && _additionalBinaryDataProperties?.ContainsKey("input_audio_format") != true)
            {
                writer.WritePropertyName("input_audio_format"u8);
                writer.WriteStringValue(InputAudioFormat.Value.ToString());
            }
            if (Optional.IsDefined(OutputAudioFormat) && _additionalBinaryDataProperties?.ContainsKey("output_audio_format") != true)
            {
                writer.WritePropertyName("output_audio_format"u8);
                writer.WriteStringValue(OutputAudioFormat.Value.ToString());
            }
            if (Optional.IsCollectionDefined(Tools) && _additionalBinaryDataProperties?.ContainsKey("tools") != true)
            {
                writer.WritePropertyName("tools"u8);
                writer.WriteStartArray();
                foreach (ConversationTool item in Tools)
                {
                    writer.WriteObjectValue(item, options);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true)
            {
                writer.WritePropertyName("temperature"u8);
                writer.WriteNumberValue(Temperature.Value);
            }
            if (Optional.IsDefined(Model) && _additionalBinaryDataProperties?.ContainsKey("model") != true)
            {
                writer.WritePropertyName("model"u8);
                writer.WriteStringValue(Model.Value.ToString());
            }
            if (Optional.IsDefined(TurnDetectionOptions) && _additionalBinaryDataProperties?.ContainsKey("turn_detection") != true)
            {
                if (TurnDetectionOptions != null)
                {
                    writer.WritePropertyName("turn_detection"u8);
                    writer.WriteObjectValue<ConversationTurnDetectionOptions>(TurnDetectionOptions, options);
                }
                else
                {
                    writer.WriteNull("turnDetection"u8);
                }
            }
            if (Optional.IsDefined(InputTranscriptionOptions) && _additionalBinaryDataProperties?.ContainsKey("input_audio_transcription") != true)
            {
                if (InputTranscriptionOptions != null)
                {
                    writer.WritePropertyName("input_audio_transcription"u8);
                    writer.WriteObjectValue<ConversationInputTranscriptionOptions>(InputTranscriptionOptions, options);
                }
                else
                {
                    writer.WriteNull("inputAudioTranscription"u8);
                }
            }
            if (Optional.IsCollectionDefined(_internalModalities) && _additionalBinaryDataProperties?.ContainsKey("modalities") != true)
            {
                writer.WritePropertyName("modalities"u8);
                writer.WriteStartArray();
                foreach (InternalRealtimeRequestSessionModality item in _internalModalities)
                {
                    writer.WriteStringValue(item.ToString());
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(_internalToolChoice) && _additionalBinaryDataProperties?.ContainsKey("tool_choice") != true)
            {
                writer.WritePropertyName("tool_choice"u8);
#if NET6_0_OR_GREATER
                writer.WriteRawValue(_internalToolChoice);
#else
                using (JsonDocument document = JsonDocument.Parse(_internalToolChoice))
                {
                    JsonSerializer.Serialize(writer, document.RootElement);
                }
#endif
            }
            if (Optional.IsDefined(_maxResponseOutputTokens) && _additionalBinaryDataProperties?.ContainsKey("max_response_output_tokens") != true)
            {
                writer.WritePropertyName("max_response_output_tokens"u8);
#if NET6_0_OR_GREATER
                writer.WriteRawValue(_maxResponseOutputTokens);
#else
                using (JsonDocument document = JsonDocument.Parse(_maxResponseOutputTokens))
                {
                    JsonSerializer.Serialize(writer, document.RootElement);
                }
#endif
            }
            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
                }
            }
        }

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

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

        internal static ConversationSessionOptions DeserializeConversationSessionOptions(JsonElement element, ModelReaderWriterOptions options)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return null;
            }
            string instructions = default;
            ConversationVoice? voice = default;
            ConversationAudioFormat? inputAudioFormat = default;
            ConversationAudioFormat? outputAudioFormat = default;
            IList<ConversationTool> tools = default;
            float? temperature = default;
            InternalRealtimeRequestSessionModel? model = default;
            ConversationTurnDetectionOptions turnDetectionOptions = default;
            ConversationInputTranscriptionOptions inputTranscriptionOptions = default;
            IList<InternalRealtimeRequestSessionModality> internalModalities = default;
            BinaryData internalToolChoice = default;
            BinaryData maxResponseOutputTokens = default;
            IDictionary<string, BinaryData> additionalBinaryDataProperties = new ChangeTrackingDictionary<string, BinaryData>();
            foreach (var prop in element.EnumerateObject())
            {
                if (prop.NameEquals("instructions"u8))
                {
                    instructions = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("voice"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    voice = new ConversationVoice(prop.Value.GetString());
                    continue;
                }
                if (prop.NameEquals("input_audio_format"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    inputAudioFormat = new ConversationAudioFormat(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 (prop.NameEquals("tools"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<ConversationTool> array = new List<ConversationTool>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(ConversationTool.DeserializeConversationTool(item, options));
                    }
                    tools = array;
                    continue;
                }
                if (prop.NameEquals("temperature"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    temperature = prop.Value.GetSingle();
                    continue;
                }
                if (prop.NameEquals("model"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    model = new InternalRealtimeRequestSessionModel(prop.Value.GetString());
                    continue;
                }
                if (prop.NameEquals("turn_detection"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        turnDetectionOptions = null;
                        continue;
                    }
                    turnDetectionOptions = ConversationTurnDetectionOptions.DeserializeConversationTurnDetectionOptions(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("input_audio_transcription"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        inputTranscriptionOptions = null;
                        continue;
                    }
                    inputTranscriptionOptions = ConversationInputTranscriptionOptions.DeserializeConversationInputTranscriptionOptions(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("modalities"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<InternalRealtimeRequestSessionModality> array = new List<InternalRealtimeRequestSessionModality>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(new InternalRealtimeRequestSessionModality(item.GetString()));
                    }
                    internalModalities = array;
                    continue;
                }
                if (prop.NameEquals("tool_choice"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    internalToolChoice = BinaryData.FromString(prop.Value.GetRawText());
                    continue;
                }
                if (prop.NameEquals("max_response_output_tokens"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    maxResponseOutputTokens = BinaryData.FromString(prop.Value.GetRawText());
                    continue;
                }
                if (true)
                {
                    additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText()));
                }
            }
            return new ConversationSessionOptions(
                instructions,
                voice,
                inputAudioFormat,
                outputAudioFormat,
                tools ?? new ChangeTrackingList<ConversationTool>(),
                temperature,
                model,
                turnDetectionOptions,
                inputTranscriptionOptions,
                internalModalities,
                internalToolChoice,
                maxResponseOutputTokens,
                additionalBinaryDataProperties);
        }

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

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

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

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

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

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

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