// <auto-generated/>

#nullable disable

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

namespace OpenAI.Audio
{
    public readonly partial struct TranscribedSegment : IJsonModel<TranscribedSegment>, IJsonModel<object>
    {
        public TranscribedSegment()
        {
        }

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

        private void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options)
        {
            string format = options.Format == "W" ? ((IPersistableModel<TranscribedSegment>)this).GetFormatFromOptions(options) : options.Format;
            if (format != "J")
            {
                throw new FormatException($"The model {nameof(TranscribedSegment)} does not support writing '{format}' format.");
            }
            if (_additionalBinaryDataProperties?.ContainsKey("id") != true)
            {
                writer.WritePropertyName("id"u8);
                writer.WriteNumberValue(Id);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("text") != true)
            {
                writer.WritePropertyName("text"u8);
                writer.WriteStringValue(Text);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("temperature") != true)
            {
                writer.WritePropertyName("temperature"u8);
                writer.WriteNumberValue(Temperature);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("compression_ratio") != true)
            {
                writer.WritePropertyName("compression_ratio"u8);
                writer.WriteNumberValue(CompressionRatio);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("start") != true)
            {
                writer.WritePropertyName("start"u8);
                writer.WriteNumberValue(Convert.ToDouble(StartTime.ToString("s\\.FFF")));
            }
            if (_additionalBinaryDataProperties?.ContainsKey("end") != true)
            {
                writer.WritePropertyName("end"u8);
                writer.WriteNumberValue(Convert.ToDouble(EndTime.ToString("s\\.FFF")));
            }
            if (_additionalBinaryDataProperties?.ContainsKey("seek") != true)
            {
                writer.WritePropertyName("seek"u8);
                writer.WriteNumberValue(SeekOffset);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("tokens") != true)
            {
                writer.WritePropertyName("tokens"u8);
                writer.WriteStartArray();
                foreach (int item in TokenIds.Span)
                {
                    writer.WriteNumberValue(item);
                }
                writer.WriteEndArray();
            }
            if (_additionalBinaryDataProperties?.ContainsKey("avg_logprob") != true)
            {
                writer.WritePropertyName("avg_logprob"u8);
                writer.WriteNumberValue(AverageLogProbability);
            }
            if (_additionalBinaryDataProperties?.ContainsKey("no_speech_prob") != true)
            {
                writer.WritePropertyName("no_speech_prob"u8);
                writer.WriteNumberValue(NoSpeechProbability);
            }
            // 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
                }
            }
        }

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

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

        internal static TranscribedSegment DeserializeTranscribedSegment(JsonElement element, ModelReaderWriterOptions options)
        {
            if (element.ValueKind == JsonValueKind.Null)
            {
                return default;
            }
            int id = default;
            string text = default;
            float temperature = default;
            float compressionRatio = default;
            TimeSpan startTime = default;
            TimeSpan endTime = default;
            int seekOffset = default;
            ReadOnlyMemory<int> tokenIds = default;
            float averageLogProbability = default;
            float noSpeechProbability = default;
            IDictionary<string, BinaryData> additionalBinaryDataProperties = new ChangeTrackingDictionary<string, BinaryData>();
            foreach (var prop in element.EnumerateObject())
            {
                if (prop.NameEquals("id"u8))
                {
                    id = prop.Value.GetInt32();
                    continue;
                }
                if (prop.NameEquals("text"u8))
                {
                    text = prop.Value.GetString();
                    continue;
                }
                if (prop.NameEquals("temperature"u8))
                {
                    temperature = prop.Value.GetSingle();
                    continue;
                }
                if (prop.NameEquals("compression_ratio"u8))
                {
                    compressionRatio = prop.Value.GetSingle();
                    continue;
                }
                if (prop.NameEquals("start"u8))
                {
                    startTime = TimeSpan.FromSeconds(prop.Value.GetDouble());
                    continue;
                }
                if (prop.NameEquals("end"u8))
                {
                    endTime = TimeSpan.FromSeconds(prop.Value.GetDouble());
                    continue;
                }
                if (prop.NameEquals("seek"u8))
                {
                    seekOffset = prop.Value.GetInt32();
                    continue;
                }
                if (prop.NameEquals("tokens"u8))
                {
                    if (prop.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    int index = 0;
                    int[] array = new int[prop.Value.GetArrayLength()];
                    foreach (var item in prop.Value.EnumerateArray())
                    {
                        array[index] = item.GetInt32();
                        index++;
                    }
                    tokenIds = new ReadOnlyMemory<int>(array);
                    continue;
                }
                if (prop.NameEquals("avg_logprob"u8))
                {
                    averageLogProbability = prop.Value.GetSingle();
                    continue;
                }
                if (prop.NameEquals("no_speech_prob"u8))
                {
                    noSpeechProbability = prop.Value.GetSingle();
                    continue;
                }
                // Plugin customization: remove options.Format != "W" check
                additionalBinaryDataProperties.Add(prop.Name, BinaryData.FromString(prop.Value.GetRawText()));
            }
            return new TranscribedSegment(
                id,
                text,
                temperature,
                compressionRatio,
                startTime,
                endTime,
                seekOffset,
                tokenIds,
                averageLogProbability,
                noSpeechProbability,
                additionalBinaryDataProperties);
        }

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

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

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

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

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

        void IJsonModel<object>.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options) => ((IJsonModel<TranscribedSegment>)this).Write(writer, options);

        object IJsonModel<object>.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options) => ((IJsonModel<TranscribedSegment>)this).Create(ref reader, options);

        BinaryData IPersistableModel<object>.Write(ModelReaderWriterOptions options) => ((IPersistableModel<TranscribedSegment>)this).Write(options);

        string IPersistableModel<object>.GetFormatFromOptions(ModelReaderWriterOptions options) => ((IPersistableModel<TranscribedSegment>)this).GetFormatFromOptions(options);

        object IPersistableModel<object>.Create(BinaryData data, ModelReaderWriterOptions options) => ((IPersistableModel<TranscribedSegment>)this).Create(data, options);
    }
}
