// <auto-generated/>

#nullable disable

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

namespace OpenAI.Assistants
{
    public partial class ThreadRun : IJsonModel<ThreadRun>
    {
        internal ThreadRun() : this(null, default, null, null, default, null, default, default, default, default, default, null, null, null, null, null, null, default, null, null, null, null, default, default, default, default, null, null)
        {
        }

        void IJsonModel<ThreadRun>.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<ThreadRun>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(ThreadRun)} does not support writing '{format}' format.");
            }
            if (_additionalBinaryDataProperties?.ContainsKey("id") != true)
            {
                writer.WritePropertyName("id"u8);
                writer.WriteStringValue(Id);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("created_at") != true)
            {
                writer.WritePropertyName("created_at"u8);
                writer.WriteNumberValue(CreatedAt, "U");
            }
            if (_additionalBinaryDataProperties?.ContainsKey("thread_id") != true)
            {
                writer.WritePropertyName("thread_id"u8);
                writer.WriteStringValue(ThreadId);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("assistant_id") != true)
            {
                writer.WritePropertyName("assistant_id"u8);
                writer.WriteStringValue(AssistantId);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("status") != true)
            {
                writer.WritePropertyName("status"u8);
                writer.WriteStringValue(Status.ToString());
            }
            if (_additionalBinaryDataProperties?.ContainsKey("last_error") != true)
            {
                if (Optional.IsDefined(LastError))
                {
                    writer.WritePropertyName("last_error"u8);
                    writer.WriteObjectValue(LastError, options);
                }
                else
                {
                    writer.WriteNull("last_error"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("expires_at") != true)
            {
                if (Optional.IsDefined(ExpiresAt))
                {
                    writer.WritePropertyName("expires_at"u8);
                    writer.WriteNumberValue(ExpiresAt.Value, "U");
                }
                else
                {
                    writer.WriteNull("expires_at"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("started_at") != true)
            {
                if (Optional.IsDefined(StartedAt))
                {
                    writer.WritePropertyName("started_at"u8);
                    writer.WriteNumberValue(StartedAt.Value, "U");
                }
                else
                {
                    writer.WriteNull("started_at"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("cancelled_at") != true)
            {
                if (Optional.IsDefined(CancelledAt))
                {
                    writer.WritePropertyName("cancelled_at"u8);
                    writer.WriteNumberValue(CancelledAt.Value, "U");
                }
                else
                {
                    writer.WriteNull("cancelled_at"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("failed_at") != true)
            {
                if (Optional.IsDefined(FailedAt))
                {
                    writer.WritePropertyName("failed_at"u8);
                    writer.WriteNumberValue(FailedAt.Value, "U");
                }
                else
                {
                    writer.WriteNull("failed_at"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("completed_at") != true)
            {
                if (Optional.IsDefined(CompletedAt))
                {
                    writer.WritePropertyName("completed_at"u8);
                    writer.WriteNumberValue(CompletedAt.Value, "U");
                }
                else
                {
                    writer.WriteNull("completed_at"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("incomplete_details") != true)
            {
                if (Optional.IsDefined(IncompleteDetails))
                {
                    writer.WritePropertyName("incomplete_details"u8);
                    writer.WriteObjectValue(IncompleteDetails, options);
                }
                else
                {
                    writer.WriteNull("incomplete_details"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("model") != true)
            {
                writer.WritePropertyName("model"u8);
                writer.WriteStringValue(Model);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("instructions") != true)
            {
                writer.WritePropertyName("instructions"u8);
                writer.WriteStringValue(Instructions);
            }
            // Plugin customization: remove options.Format != "W" check
            if (_additionalBinaryDataProperties?.ContainsKey("tools") != true)
            {
                writer.WritePropertyName("tools"u8);
                writer.WriteStartArray();
                foreach (ToolDefinition item in Tools)
                {
                    writer.WriteObjectValue(item, options);
                }
                writer.WriteEndArray();
            }
            // Plugin customization: remove options.Format != "W" check
            if (_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 (_additionalBinaryDataProperties?.ContainsKey("usage") != true)
            {
                if (Optional.IsDefined(Usage))
                {
                    writer.WritePropertyName("usage"u8);
                    writer.WriteObjectValue(Usage, options);
                }
                else
                {
                    writer.WriteNull("usage"u8);
                }
            }
            if (Optional.IsDefined(Temperature) && _additionalBinaryDataProperties?.ContainsKey("temperature") != true)
            {
                writer.WritePropertyName("temperature"u8);
                writer.WriteNumberValue(Temperature.Value);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("truncation_strategy") != true)
            {
                if (Optional.IsDefined(TruncationStrategy))
                {
                    writer.WritePropertyName("truncation_strategy"u8);
                    writer.WriteObjectValue(TruncationStrategy, options);
                }
                else
                {
                    writer.WriteNull("truncation_strategy"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("object") != true)
            {
                writer.WritePropertyName("object"u8);
                writer.WriteStringValue(Object);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("response_format") != true)
            {
                if (Optional.IsDefined(ResponseFormat))
                {
                    writer.WritePropertyName("response_format"u8);
                    writer.WriteObjectValue(ResponseFormat, options);
                }
                else
                {
                    writer.WriteNull("response_format"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("tool_choice") != true)
            {
                if (Optional.IsDefined(ToolConstraint))
                {
                    writer.WritePropertyName("tool_choice"u8);
                    writer.WriteObjectValue(ToolConstraint, options);
                }
                else
                {
                    writer.WriteNull("tool_choice"u8);
                }
            }
            if (Optional.IsDefined(NucleusSamplingFactor) && _additionalBinaryDataProperties?.ContainsKey("top_p") != true)
            {
                writer.WritePropertyName("top_p"u8);
                writer.WriteNumberValue(NucleusSamplingFactor.Value);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("parallel_tool_calls") != true)
            {
                writer.WritePropertyName("parallel_tool_calls"u8);
                writer.WriteBooleanValue(AllowParallelToolCalls.Value);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("max_prompt_tokens") != true)
            {
                if (Optional.IsDefined(MaxInputTokenCount))
                {
                    writer.WritePropertyName("max_prompt_tokens"u8);
                    writer.WriteNumberValue(MaxInputTokenCount.Value);
                }
                else
                {
                    writer.WriteNull("max_prompt_tokens"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("max_completion_tokens") != true)
            {
                if (Optional.IsDefined(MaxOutputTokenCount))
                {
                    writer.WritePropertyName("max_completion_tokens"u8);
                    writer.WriteNumberValue(MaxOutputTokenCount.Value);
                }
                else
                {
                    writer.WriteNull("max_completion_tokens"u8);
                }
            }
            if (_additionalBinaryDataProperties?.ContainsKey("required_action") != true)
            {
                if (Optional.IsDefined(_internalRequiredAction))
                {
                    writer.WritePropertyName("required_action"u8);
                    writer.WriteObjectValue(_internalRequiredAction, options);
                }
                else
                {
                    writer.WriteNull("required_action"u8);
                }
            }
            // 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
                }
            }
        }

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

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

        internal static ThreadRun DeserializeThreadRun(JsonElement element, ModelReaderWriterOptions options)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return null;
            }
            string id = default;
            DateTimeOffset createdAt = default;
            string threadId = default;
            string assistantId = default;
            RunStatus status = default;
            RunError lastError = default;
            DateTimeOffset? expiresAt = default;
            DateTimeOffset? startedAt = default;
            DateTimeOffset? cancelledAt = default;
            DateTimeOffset? failedAt = default;
            DateTimeOffset? completedAt = default;
            RunIncompleteDetails incompleteDetails = default;
            string model = default;
            string instructions = default;
            IReadOnlyList<ToolDefinition> tools = default;
            IReadOnlyDictionary<string, string> metadata = default;
            RunTokenUsage usage = default;
            float? temperature = default;
            RunTruncationStrategy truncationStrategy = default;
            string @object = default;
            AssistantResponseFormat responseFormat = default;
            ToolConstraint toolConstraint = default;
            float? nucleusSamplingFactor = default;
            bool? allowParallelToolCalls = default;
            int? maxInputTokenCount = default;
            int? maxOutputTokenCount = default;
            InternalRunRequiredAction internalRequiredAction = 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("created_at"u8))
                {
                    createdAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("thread_id"u8))
                {
                    threadId = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("assistant_id"u8))
                {
                    assistantId = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("status"u8))
                {
                    status = new RunStatus(prop.Value.GetString());
                    continue;
                }
                if (prop.NameEquals("last_error"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        lastError = null;
                        continue;
                    }
                    lastError = RunError.DeserializeRunError(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("expires_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        expiresAt = null;
                        continue;
                    }
                    expiresAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("started_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        startedAt = null;
                        continue;
                    }
                    startedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("cancelled_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        cancelledAt = null;
                        continue;
                    }
                    cancelledAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("failed_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        failedAt = null;
                        continue;
                    }
                    failedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("completed_at"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        completedAt = null;
                        continue;
                    }
                    completedAt = DateTimeOffset.FromUnixTimeSeconds(prop.Value.GetInt64());
                    continue;
                }
                if (prop.NameEquals("incomplete_details"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        incompleteDetails = null;
                        continue;
                    }
                    incompleteDetails = RunIncompleteDetails.DeserializeRunIncompleteDetails(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("model"u8))
                {
                    model = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("instructions"u8))
                {
                    instructions = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("tools"u8))
                {
                    List<ToolDefinition> array = new List<ToolDefinition>();
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array.Add(ToolDefinition.DeserializeToolDefinition(item, options));
                    }
                    tools = array;
                    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)
                    {
                        usage = null;
                        continue;
                    }
                    usage = RunTokenUsage.DeserializeRunTokenUsage(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("temperature"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        temperature = null;
                        continue;
                    }
                    temperature = prop.Value.GetSingle();
                    continue;
                }
                if (prop.NameEquals("truncation_strategy"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        truncationStrategy = null;
                        continue;
                    }
                    truncationStrategy = RunTruncationStrategy.DeserializeRunTruncationStrategy(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("object"u8))
                {
                    @object = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("response_format"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        responseFormat = null;
                        continue;
                    }
                    responseFormat = AssistantResponseFormat.DeserializeAssistantResponseFormat(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("tool_choice"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        toolConstraint = null;
                        continue;
                    }
                    toolConstraint = ToolConstraint.DeserializeToolConstraint(prop.Value, options);
                    continue;
                }
                if (prop.NameEquals("top_p"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        nucleusSamplingFactor = null;
                        continue;
                    }
                    nucleusSamplingFactor = prop.Value.GetSingle();
                    continue;
                }
                if (prop.NameEquals("parallel_tool_calls"u8))
                {
                    allowParallelToolCalls = prop.Value.GetBoolean();
                    continue;
                }
                if (prop.NameEquals("max_prompt_tokens"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        maxInputTokenCount = null;
                        continue;
                    }
                    maxInputTokenCount = prop.Value.GetInt32();
                    continue;
                }
                if (prop.NameEquals("max_completion_tokens"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        maxOutputTokenCount = null;
                        continue;
                    }
                    maxOutputTokenCount = prop.Value.GetInt32();
                    continue;
                }
                if (prop.NameEquals("required_action"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        internalRequiredAction = null;
                        continue;
                    }
                    internalRequiredAction = InternalRunRequiredAction.DeserializeInternalRunRequiredAction(prop.Value, options);
                    continue;
                }
                // Plugin customization: remove options.Format != "W" check
                additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText()));
            }
            return new ThreadRun(
                id,
                createdAt,
                threadId,
                assistantId,
                status,
                lastError,
                expiresAt,
                startedAt,
                cancelledAt,
                failedAt,
                completedAt,
                incompleteDetails,
                model,
                instructions,
                tools,
                metadata,
                usage,
                temperature,
                truncationStrategy,
                @object,
                responseFormat,
                toolConstraint,
                nucleusSamplingFactor,
                allowParallelToolCalls,
                maxInputTokenCount,
                maxOutputTokenCount,
                internalRequiredAction,
                additionalBinaryDataProperties);
        }

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

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

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

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

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