// <auto-generated/>

#nullable disable

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

namespace OpenAI.Responses
{
    public partial class ResponseCreationOptions : IJsonModel<ResponseCreationOptions>
    {
        public ResponseCreationOptions() : this(null, default, default, default, null, default, null, null, null, null, default, null, null, default, null, default, default, default, null, null, null)
        {
        }

        void IJsonModel<ResponseCreationOptions>.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<ResponseCreationOptions>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(ResponseCreationOptions)} does not support writing '{format}' format.");
            }
            if (Optional.IsCollectionDefined(Metadata) && _additionalBinaryDataProperties?.ContainsKey("metadata") != true)
            {
                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();
            }
            if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true)
            {
                writer.WritePropertyName("temperature"u8);
                writer.WriteNumberValue(Temperature.Value);
            }
            if (Optional.IsDefined(TopP) && _additionalBinaryDataProperties?.ContainsKey("top_p") != true)
            {
                writer.WritePropertyName("top_p"u8);
                writer.WriteNumberValue(TopP.Value);
            }
            if (Optional.IsDefined(ServiceTier) && _additionalBinaryDataProperties?.ContainsKey("service_tier") != true)
            {
                writer.WritePropertyName("service_tier"u8);
                writer.WriteStringValue(ServiceTier.Value.ToString());
            }
            if (Optional.IsDefined(PreviousResponseId) && _additionalBinaryDataProperties?.ContainsKey("previous_response_id") != true)
            {
                writer.WritePropertyName("previous_response_id"u8);
                writer.WriteStringValue(PreviousResponseId);
            }
            if (Optional.IsDefined(Background) && _additionalBinaryDataProperties?.ContainsKey("background") != true)
            {
                writer.WritePropertyName("background"u8);
                writer.WriteBooleanValue(Background.Value);
            }
            if (Optional.IsDefined(Instructions) && _additionalBinaryDataProperties?.ContainsKey("instructions") != true)
            {
                writer.WritePropertyName("instructions"u8);
                writer.WriteStringValue(Instructions);
            }
            if (Optional.IsCollectionDefined(Include) && _additionalBinaryDataProperties?.ContainsKey("include") != true)
            {
                writer.WritePropertyName("include"u8);
                writer.WriteStartArray();
                foreach (InternalIncludable item in Include)
                {
                    writer.WriteStringValue(item.ToString());
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(Model) && _additionalBinaryDataProperties?.ContainsKey("model") != true)
            {
                writer.WritePropertyName("model"u8);
                writer.WriteStringValue(Model);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("input") != true)
            {
                writer.WritePropertyName("input"u8);
                writer.WriteStartArray();
                foreach (ResponseItem item in Input)
                {
                    writer.WriteObjectValue(item, options);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(Stream) && _additionalBinaryDataProperties?.ContainsKey("stream") != true)
            {
                writer.WritePropertyName("stream"u8);
                writer.WriteBooleanValue(Stream.Value);
            }
            if (Optional.IsDefined(EndUserId) && _additionalBinaryDataProperties?.ContainsKey("user") != true)
            {
                writer.WritePropertyName("user"u8);
                writer.WriteStringValue(EndUserId);
            }
            if (Optional.IsDefined(ReasoningOptions) && _additionalBinaryDataProperties?.ContainsKey("reasoning") != true)
            {
                writer.WritePropertyName("reasoning"u8);
                writer.WriteObjectValue(ReasoningOptions, options);
            }
            if (Optional.IsDefined(MaxOutputTokenCount) && _additionalBinaryDataProperties?.ContainsKey("max_output_tokens") != true)
            {
                writer.WritePropertyName("max_output_tokens"u8);
                writer.WriteNumberValue(MaxOutputTokenCount.Value);
            }
            if (Optional.IsDefined(TextOptions) && _additionalBinaryDataProperties?.ContainsKey("text") != true)
            {
                writer.WritePropertyName("text"u8);
                writer.WriteObjectValue(TextOptions, options);
            }
            if (Optional.IsDefined(TruncationMode) && _additionalBinaryDataProperties?.ContainsKey("truncation") != true)
            {
                writer.WritePropertyName("truncation"u8);
                writer.WriteStringValue(TruncationMode.Value.ToString());
            }
            if (Optional.IsDefined(ParallelToolCallsEnabled) && _additionalBinaryDataProperties?.ContainsKey("parallel_tool_calls") != true)
            {
                writer.WritePropertyName("parallel_tool_calls"u8);
                writer.WriteBooleanValue(ParallelToolCallsEnabled.Value);
            }
            if (Optional.IsDefined(StoredOutputEnabled) && _additionalBinaryDataProperties?.ContainsKey("store") != true)
            {
                writer.WritePropertyName("store"u8);
                writer.WriteBooleanValue(StoredOutputEnabled.Value);
            }
            if (Optional.IsDefined(ToolChoice) && _additionalBinaryDataProperties?.ContainsKey("tool_choice") != true)
            {
                writer.WritePropertyName("tool_choice"u8);
                writer.WriteObjectValue(ToolChoice, options);
            }
            if (Optional.IsCollectionDefined(Tools) && _additionalBinaryDataProperties?.ContainsKey("tools") != true)
            {
                writer.WritePropertyName("tools"u8);
                writer.WriteStartArray();
                foreach (ResponseTool item in Tools)
                {
                    writer.WriteObjectValue(item, options);
                }
                writer.WriteEndArray();
            }
            // 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
                }
            }
        }

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

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

        internal static ResponseCreationOptions DeserializeResponseCreationOptions(JsonElement element, ModelReaderWriterOptions options)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return null;
            }
            IDictionary<string, string> metadata = default;
            float? temperature = default;
            float? topP = default;
            InternalServiceTier? serviceTier = default;
            string previousResponseId = default;
            bool? background = default;
            string instructions = default;
            IList<InternalIncludable> include = default;
            string model = default;
            IList<ResponseItem> input = default;
            bool? stream = default;
            string endUserId = default;
            ResponseReasoningOptions reasoningOptions = default;
            int? maxOutputTokenCount = default;
            ResponseTextOptions textOptions = default;
            ResponseTruncationMode? truncationMode = default;
            bool? parallelToolCallsEnabled = default;
            bool? storedOutputEnabled = default;
            ResponseToolChoice toolChoice = default;
            IList<ResponseTool> tools = default;
            IDictionary<string, BinaryData> additionalBinaryDataProperties = new ChangeTrackingDictionary<string, BinaryData>();
            foreach (var prop in element.EnumerateObject())
            {
                if (prop.NameEquals("metadata"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        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("temperature"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        temperature = null;
                        continue;
                    }
                    temperature = prop.Value.GetSingle();
                    continue;
                }
                if (prop.NameEquals("top_p"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        topP = null;
                        continue;
                    }
                    topP = prop.Value.GetSingle();
                    continue;
                }
                if (prop.NameEquals("service_tier"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    serviceTier = new InternalServiceTier(prop.Value.GetString());
                    continue;
                }
                if (prop.NameEquals("previous_response_id"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        previousResponseId = null;
                        continue;
                    }
                    previousResponseId = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("background"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        background = null;
                        continue;
                    }
                    background = prop.Value.GetBoolean();
                    continue;
                }
                if (prop.NameEquals("instructions"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        instructions = null;
                        continue;
                    }
                    instructions = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("include"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<InternalIncludable> array = new List<InternalIncludable>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(new InternalIncludable(item.GetString()));
                    }
                    include = array;
                    continue;
                }
                if (prop.NameEquals("model"u8))
                {
                    model = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("input"u8))
                {
                    List<ResponseItem> array = new List<ResponseItem>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(ResponseItem.DeserializeResponseItem(item, options));
                    }
                    input = array;
                    continue;
                }
                if (prop.NameEquals("stream"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        stream = null;
                        continue;
                    }
                    stream = prop.Value.GetBoolean();
                    continue;
                }
                if (prop.NameEquals("user"u8))
                {
                    endUserId = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("reasoning"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        reasoningOptions = null;
                        continue;
                    }
                    reasoningOptions = ResponseReasoningOptions.DeserializeResponseReasoningOptions(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("max_output_tokens"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        maxOutputTokenCount = null;
                        continue;
                    }
                    maxOutputTokenCount = prop.Value.GetInt32();
                    continue;
                }
                if (prop.NameEquals("text"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    textOptions = ResponseTextOptions.DeserializeResponseTextOptions(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("truncation"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        truncationMode = null;
                        continue;
                    }
                    truncationMode = new ResponseTruncationMode(prop.Value.GetString());
                    continue;
                }
                if (prop.NameEquals("parallel_tool_calls"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        parallelToolCallsEnabled = null;
                        continue;
                    }
                    parallelToolCallsEnabled = prop.Value.GetBoolean();
                    continue;
                }
                if (prop.NameEquals("store"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        storedOutputEnabled = null;
                        continue;
                    }
                    storedOutputEnabled = prop.Value.GetBoolean();
                    continue;
                }
                if (prop.NameEquals("tool_choice"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    toolChoice = ResponseToolChoice.DeserializeResponseToolChoice(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("tools"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<ResponseTool> array = new List<ResponseTool>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(ResponseTool.DeserializeResponseTool(item, options));
                    }
                    tools = array;
                    continue;
                }
                // Plugin customization: remove options.Format != "W" check
                additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText()));
            }
            return new ResponseCreationOptions(
                metadata ?? new ChangeTrackingDictionary<string, string>(),
                temperature,
                topP,
                serviceTier,
                previousResponseId,
                background,
                instructions,
                include ?? new ChangeTrackingList<InternalIncludable>(),
                model,
                input,
                stream,
                endUserId,
                reasoningOptions,
                maxOutputTokenCount,
                textOptions,
                truncationMode,
                parallelToolCallsEnabled,
                storedOutputEnabled,
                toolChoice,
                tools ?? new ChangeTrackingList<ResponseTool>(),
                additionalBinaryDataProperties);
        }

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

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

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

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

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