// File generated from our OpenAPI spec by Stainless.

package com.openai.models.chat.completions

import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonAnySetter
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.ObjectCodec
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.module.kotlin.jacksonTypeRef
import com.openai.core.BaseDeserializer
import com.openai.core.BaseSerializer
import com.openai.core.ExcludeMissing
import com.openai.core.JsonField
import com.openai.core.JsonMissing
import com.openai.core.JsonValue
import com.openai.core.allMaxBy
import com.openai.core.checkKnown
import com.openai.core.checkRequired
import com.openai.core.getOrThrow
import com.openai.core.toImmutable
import com.openai.errors.OpenAIInvalidDataException
import java.util.Collections
import java.util.Objects
import java.util.Optional
import kotlin.jvm.optionals.getOrNull

/** A chat completion message generated by the model. */
class ChatCompletionStoreMessage
@JsonCreator(mode = JsonCreator.Mode.DISABLED)
private constructor(
    private val content: JsonField<String>,
    private val refusal: JsonField<String>,
    private val role: JsonValue,
    private val annotations: JsonField<List<ChatCompletionMessage.Annotation>>,
    private val audio: JsonField<ChatCompletionAudio>,
    private val functionCall: JsonField<ChatCompletionMessage.FunctionCall>,
    private val toolCalls: JsonField<List<ChatCompletionMessageToolCall>>,
    private val id: JsonField<String>,
    private val contentParts: JsonField<List<ContentPart>>,
    private val additionalProperties: MutableMap<String, JsonValue>,
) {

    @JsonCreator
    private constructor(
        @JsonProperty("content") @ExcludeMissing content: JsonField<String> = JsonMissing.of(),
        @JsonProperty("refusal") @ExcludeMissing refusal: JsonField<String> = JsonMissing.of(),
        @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(),
        @JsonProperty("annotations")
        @ExcludeMissing
        annotations: JsonField<List<ChatCompletionMessage.Annotation>> = JsonMissing.of(),
        @JsonProperty("audio")
        @ExcludeMissing
        audio: JsonField<ChatCompletionAudio> = JsonMissing.of(),
        @JsonProperty("function_call")
        @ExcludeMissing
        functionCall: JsonField<ChatCompletionMessage.FunctionCall> = JsonMissing.of(),
        @JsonProperty("tool_calls")
        @ExcludeMissing
        toolCalls: JsonField<List<ChatCompletionMessageToolCall>> = JsonMissing.of(),
        @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
        @JsonProperty("content_parts")
        @ExcludeMissing
        contentParts: JsonField<List<ContentPart>> = JsonMissing.of(),
    ) : this(
        content,
        refusal,
        role,
        annotations,
        audio,
        functionCall,
        toolCalls,
        id,
        contentParts,
        mutableMapOf(),
    )

    fun toChatCompletionMessage(): ChatCompletionMessage =
        ChatCompletionMessage.builder()
            .content(content)
            .refusal(refusal)
            .role(role)
            .annotations(annotations)
            .audio(audio)
            .functionCall(functionCall)
            .toolCalls(toolCalls)
            .build()

    /**
     * The contents of the message.
     *
     * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
     *   server responded with an unexpected value).
     */
    fun content(): Optional<String> = content.getOptional("content")

    /**
     * The refusal message generated by the model.
     *
     * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
     *   server responded with an unexpected value).
     */
    fun refusal(): Optional<String> = refusal.getOptional("refusal")

    /**
     * The role of the author of this message.
     *
     * Expected to always return the following:
     * ```java
     * JsonValue.from("assistant")
     * ```
     *
     * However, this method can be useful for debugging and logging (e.g. if the server responded
     * with an unexpected value).
     */
    @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role

    /**
     * Annotations for the message, when applicable, as when using the
     * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).
     *
     * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
     *   server responded with an unexpected value).
     */
    fun annotations(): Optional<List<ChatCompletionMessage.Annotation>> =
        annotations.getOptional("annotations")

    /**
     * If the audio output modality is requested, this object contains data about the audio response
     * from the model. [Learn more](https://platform.openai.com/docs/guides/audio).
     *
     * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
     *   server responded with an unexpected value).
     */
    fun audio(): Optional<ChatCompletionAudio> = audio.getOptional("audio")

    /**
     * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be
     * called, as generated by the model.
     *
     * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
     *   server responded with an unexpected value).
     */
    @Deprecated("deprecated")
    fun functionCall(): Optional<ChatCompletionMessage.FunctionCall> =
        functionCall.getOptional("function_call")

    /**
     * The tool calls generated by the model, such as function calls.
     *
     * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
     *   server responded with an unexpected value).
     */
    fun toolCalls(): Optional<List<ChatCompletionMessageToolCall>> =
        toolCalls.getOptional("tool_calls")

    /**
     * The identifier of the chat message.
     *
     * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
     *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
     */
    fun id(): String = id.getRequired("id")

    /**
     * If a content parts array was provided, this is an array of `text` and `image_url` parts.
     * Otherwise, null.
     *
     * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
     *   server responded with an unexpected value).
     */
    fun contentParts(): Optional<List<ContentPart>> = contentParts.getOptional("content_parts")

    /**
     * Returns the raw JSON value of [content].
     *
     * Unlike [content], this method doesn't throw if the JSON field has an unexpected type.
     */
    @JsonProperty("content") @ExcludeMissing fun _content(): JsonField<String> = content

    /**
     * Returns the raw JSON value of [refusal].
     *
     * Unlike [refusal], this method doesn't throw if the JSON field has an unexpected type.
     */
    @JsonProperty("refusal") @ExcludeMissing fun _refusal(): JsonField<String> = refusal

    /**
     * Returns the raw JSON value of [annotations].
     *
     * Unlike [annotations], this method doesn't throw if the JSON field has an unexpected type.
     */
    @JsonProperty("annotations")
    @ExcludeMissing
    fun _annotations(): JsonField<List<ChatCompletionMessage.Annotation>> = annotations

    /**
     * Returns the raw JSON value of [audio].
     *
     * Unlike [audio], this method doesn't throw if the JSON field has an unexpected type.
     */
    @JsonProperty("audio") @ExcludeMissing fun _audio(): JsonField<ChatCompletionAudio> = audio

    /**
     * Returns the raw JSON value of [functionCall].
     *
     * Unlike [functionCall], this method doesn't throw if the JSON field has an unexpected type.
     */
    @Deprecated("deprecated")
    @JsonProperty("function_call")
    @ExcludeMissing
    fun _functionCall(): JsonField<ChatCompletionMessage.FunctionCall> = functionCall

    /**
     * Returns the raw JSON value of [toolCalls].
     *
     * Unlike [toolCalls], this method doesn't throw if the JSON field has an unexpected type.
     */
    @JsonProperty("tool_calls")
    @ExcludeMissing
    fun _toolCalls(): JsonField<List<ChatCompletionMessageToolCall>> = toolCalls

    /**
     * Returns the raw JSON value of [id].
     *
     * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
     */
    @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

    /**
     * Returns the raw JSON value of [contentParts].
     *
     * Unlike [contentParts], this method doesn't throw if the JSON field has an unexpected type.
     */
    @JsonProperty("content_parts")
    @ExcludeMissing
    fun _contentParts(): JsonField<List<ContentPart>> = contentParts

    @JsonAnySetter
    private fun putAdditionalProperty(key: String, value: JsonValue) {
        additionalProperties.put(key, value)
    }

    @JsonAnyGetter
    @ExcludeMissing
    fun _additionalProperties(): Map<String, JsonValue> =
        Collections.unmodifiableMap(additionalProperties)

    fun toBuilder() = Builder().from(this)

    companion object {

        /**
         * Returns a mutable builder for constructing an instance of [ChatCompletionStoreMessage].
         *
         * The following fields are required:
         * ```java
         * .content()
         * .refusal()
         * .id()
         * ```
         */
        @JvmStatic fun builder() = Builder()
    }

    /** A builder for [ChatCompletionStoreMessage]. */
    class Builder internal constructor() {

        private var content: JsonField<String>? = null
        private var refusal: JsonField<String>? = null
        private var role: JsonValue = JsonValue.from("assistant")
        private var annotations: JsonField<MutableList<ChatCompletionMessage.Annotation>>? = null
        private var audio: JsonField<ChatCompletionAudio> = JsonMissing.of()
        private var functionCall: JsonField<ChatCompletionMessage.FunctionCall> = JsonMissing.of()
        private var toolCalls: JsonField<MutableList<ChatCompletionMessageToolCall>>? = null
        private var id: JsonField<String>? = null
        private var contentParts: JsonField<MutableList<ContentPart>>? = null
        private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

        @JvmSynthetic
        internal fun from(chatCompletionStoreMessage: ChatCompletionStoreMessage) = apply {
            content = chatCompletionStoreMessage.content
            refusal = chatCompletionStoreMessage.refusal
            role = chatCompletionStoreMessage.role
            annotations = chatCompletionStoreMessage.annotations.map { it.toMutableList() }
            audio = chatCompletionStoreMessage.audio
            functionCall = chatCompletionStoreMessage.functionCall
            toolCalls = chatCompletionStoreMessage.toolCalls.map { it.toMutableList() }
            id = chatCompletionStoreMessage.id
            contentParts = chatCompletionStoreMessage.contentParts.map { it.toMutableList() }
            additionalProperties = chatCompletionStoreMessage.additionalProperties.toMutableMap()
        }

        /** The contents of the message. */
        fun content(content: String?) = content(JsonField.ofNullable(content))

        /** Alias for calling [Builder.content] with `content.orElse(null)`. */
        fun content(content: Optional<String>) = content(content.getOrNull())

        /**
         * Sets [Builder.content] to an arbitrary JSON value.
         *
         * You should usually call [Builder.content] with a well-typed [String] value instead. This
         * method is primarily for setting the field to an undocumented or not yet supported value.
         */
        fun content(content: JsonField<String>) = apply { this.content = content }

        /** The refusal message generated by the model. */
        fun refusal(refusal: String?) = refusal(JsonField.ofNullable(refusal))

        /** Alias for calling [Builder.refusal] with `refusal.orElse(null)`. */
        fun refusal(refusal: Optional<String>) = refusal(refusal.getOrNull())

        /**
         * Sets [Builder.refusal] to an arbitrary JSON value.
         *
         * You should usually call [Builder.refusal] with a well-typed [String] value instead. This
         * method is primarily for setting the field to an undocumented or not yet supported value.
         */
        fun refusal(refusal: JsonField<String>) = apply { this.refusal = refusal }

        /**
         * Sets the field to an arbitrary JSON value.
         *
         * It is usually unnecessary to call this method because the field defaults to the
         * following:
         * ```java
         * JsonValue.from("assistant")
         * ```
         *
         * This method is primarily for setting the field to an undocumented or not yet supported
         * value.
         */
        fun role(role: JsonValue) = apply { this.role = role }

        /**
         * Annotations for the message, when applicable, as when using the
         * [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).
         */
        fun annotations(annotations: List<ChatCompletionMessage.Annotation>) =
            annotations(JsonField.of(annotations))

        /**
         * Sets [Builder.annotations] to an arbitrary JSON value.
         *
         * You should usually call [Builder.annotations] with a well-typed
         * `List<ChatCompletionMessage.Annotation>` value instead. This method is primarily for
         * setting the field to an undocumented or not yet supported value.
         */
        fun annotations(annotations: JsonField<List<ChatCompletionMessage.Annotation>>) = apply {
            this.annotations = annotations.map { it.toMutableList() }
        }

        /**
         * Adds a single [ChatCompletionMessage.Annotation] to [annotations].
         *
         * @throws IllegalStateException if the field was previously set to a non-list.
         */
        fun addAnnotation(annotation: ChatCompletionMessage.Annotation) = apply {
            annotations =
                (annotations ?: JsonField.of(mutableListOf())).also {
                    checkKnown("annotations", it).add(annotation)
                }
        }

        /**
         * If the audio output modality is requested, this object contains data about the audio
         * response from the model. [Learn more](https://platform.openai.com/docs/guides/audio).
         */
        fun audio(audio: ChatCompletionAudio?) = audio(JsonField.ofNullable(audio))

        /** Alias for calling [Builder.audio] with `audio.orElse(null)`. */
        fun audio(audio: Optional<ChatCompletionAudio>) = audio(audio.getOrNull())

        /**
         * Sets [Builder.audio] to an arbitrary JSON value.
         *
         * You should usually call [Builder.audio] with a well-typed [ChatCompletionAudio] value
         * instead. This method is primarily for setting the field to an undocumented or not yet
         * supported value.
         */
        fun audio(audio: JsonField<ChatCompletionAudio>) = apply { this.audio = audio }

        /**
         * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should
         * be called, as generated by the model.
         */
        @Deprecated("deprecated")
        fun functionCall(functionCall: ChatCompletionMessage.FunctionCall) =
            functionCall(JsonField.of(functionCall))

        /**
         * Sets [Builder.functionCall] to an arbitrary JSON value.
         *
         * You should usually call [Builder.functionCall] with a well-typed
         * [ChatCompletionMessage.FunctionCall] value instead. This method is primarily for setting
         * the field to an undocumented or not yet supported value.
         */
        @Deprecated("deprecated")
        fun functionCall(functionCall: JsonField<ChatCompletionMessage.FunctionCall>) = apply {
            this.functionCall = functionCall
        }

        /** The tool calls generated by the model, such as function calls. */
        fun toolCalls(toolCalls: List<ChatCompletionMessageToolCall>) =
            toolCalls(JsonField.of(toolCalls))

        /**
         * Sets [Builder.toolCalls] to an arbitrary JSON value.
         *
         * You should usually call [Builder.toolCalls] with a well-typed
         * `List<ChatCompletionMessageToolCall>` value instead. This method is primarily for setting
         * the field to an undocumented or not yet supported value.
         */
        fun toolCalls(toolCalls: JsonField<List<ChatCompletionMessageToolCall>>) = apply {
            this.toolCalls = toolCalls.map { it.toMutableList() }
        }

        /**
         * Adds a single [ChatCompletionMessageToolCall] to [toolCalls].
         *
         * @throws IllegalStateException if the field was previously set to a non-list.
         */
        fun addToolCall(toolCall: ChatCompletionMessageToolCall) = apply {
            toolCalls =
                (toolCalls ?: JsonField.of(mutableListOf())).also {
                    checkKnown("toolCalls", it).add(toolCall)
                }
        }

        /**
         * Alias for calling [addToolCall] with
         * `ChatCompletionMessageToolCall.ofFunction(function)`.
         */
        fun addToolCall(function: ChatCompletionMessageFunctionToolCall) =
            addToolCall(ChatCompletionMessageToolCall.ofFunction(function))

        /**
         * Alias for calling [addToolCall] with `ChatCompletionMessageToolCall.ofCustom(custom)`.
         */
        fun addToolCall(custom: ChatCompletionMessageCustomToolCall) =
            addToolCall(ChatCompletionMessageToolCall.ofCustom(custom))

        /** The identifier of the chat message. */
        fun id(id: String) = id(JsonField.of(id))

        /**
         * Sets [Builder.id] to an arbitrary JSON value.
         *
         * You should usually call [Builder.id] with a well-typed [String] value instead. This
         * method is primarily for setting the field to an undocumented or not yet supported value.
         */
        fun id(id: JsonField<String>) = apply { this.id = id }

        /**
         * If a content parts array was provided, this is an array of `text` and `image_url` parts.
         * Otherwise, null.
         */
        fun contentParts(contentParts: List<ContentPart>?) =
            contentParts(JsonField.ofNullable(contentParts))

        /** Alias for calling [Builder.contentParts] with `contentParts.orElse(null)`. */
        fun contentParts(contentParts: Optional<List<ContentPart>>) =
            contentParts(contentParts.getOrNull())

        /**
         * Sets [Builder.contentParts] to an arbitrary JSON value.
         *
         * You should usually call [Builder.contentParts] with a well-typed `List<ContentPart>`
         * value instead. This method is primarily for setting the field to an undocumented or not
         * yet supported value.
         */
        fun contentParts(contentParts: JsonField<List<ContentPart>>) = apply {
            this.contentParts = contentParts.map { it.toMutableList() }
        }

        /**
         * Adds a single [ContentPart] to [contentParts].
         *
         * @throws IllegalStateException if the field was previously set to a non-list.
         */
        fun addContentPart(contentPart: ContentPart) = apply {
            contentParts =
                (contentParts ?: JsonField.of(mutableListOf())).also {
                    checkKnown("contentParts", it).add(contentPart)
                }
        }

        /**
         * Alias for calling [addContentPart] with
         * `ContentPart.ofChatCompletionContentPartText(chatCompletionContentPartText)`.
         */
        fun addContentPart(chatCompletionContentPartText: ChatCompletionContentPartText) =
            addContentPart(
                ContentPart.ofChatCompletionContentPartText(chatCompletionContentPartText)
            )

        /**
         * Alias for calling [addContentPart] with
         * `ContentPart.ofChatCompletionContentPartImage(chatCompletionContentPartImage)`.
         */
        fun addContentPart(chatCompletionContentPartImage: ChatCompletionContentPartImage) =
            addContentPart(
                ContentPart.ofChatCompletionContentPartImage(chatCompletionContentPartImage)
            )

        fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
            this.additionalProperties.clear()
            putAllAdditionalProperties(additionalProperties)
        }

        fun putAdditionalProperty(key: String, value: JsonValue) = apply {
            additionalProperties.put(key, value)
        }

        fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
            this.additionalProperties.putAll(additionalProperties)
        }

        fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

        fun removeAllAdditionalProperties(keys: Set<String>) = apply {
            keys.forEach(::removeAdditionalProperty)
        }

        /**
         * Returns an immutable instance of [ChatCompletionStoreMessage].
         *
         * Further updates to this [Builder] will not mutate the returned instance.
         *
         * The following fields are required:
         * ```java
         * .content()
         * .refusal()
         * .id()
         * ```
         *
         * @throws IllegalStateException if any required field is unset.
         */
        fun build(): ChatCompletionStoreMessage =
            ChatCompletionStoreMessage(
                checkRequired("content", content),
                checkRequired("refusal", refusal),
                role,
                (annotations ?: JsonMissing.of()).map { it.toImmutable() },
                audio,
                functionCall,
                (toolCalls ?: JsonMissing.of()).map { it.toImmutable() },
                checkRequired("id", id),
                (contentParts ?: JsonMissing.of()).map { it.toImmutable() },
                additionalProperties.toMutableMap(),
            )
    }

    private var validated: Boolean = false

    fun validate(): ChatCompletionStoreMessage = apply {
        if (validated) {
            return@apply
        }

        content()
        refusal()
        _role().let {
            if (it != JsonValue.from("assistant")) {
                throw OpenAIInvalidDataException("'role' is invalid, received $it")
            }
        }
        annotations().ifPresent { it.forEach { it.validate() } }
        audio().ifPresent { it.validate() }
        functionCall().ifPresent { it.validate() }
        toolCalls().ifPresent { it.forEach { it.validate() } }
        id()
        contentParts().ifPresent { it.forEach { it.validate() } }
        validated = true
    }

    fun isValid(): Boolean =
        try {
            validate()
            true
        } catch (e: OpenAIInvalidDataException) {
            false
        }

    /**
     * Returns a score indicating how many valid values are contained in this object recursively.
     *
     * Used for best match union deserialization.
     */
    @JvmSynthetic
    internal fun validity(): Int =
        (if (content.asKnown().isPresent) 1 else 0) +
            (if (refusal.asKnown().isPresent) 1 else 0) +
            role.let { if (it == JsonValue.from("assistant")) 1 else 0 } +
            (annotations.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) +
            (audio.asKnown().getOrNull()?.validity() ?: 0) +
            (functionCall.asKnown().getOrNull()?.validity() ?: 0) +
            (toolCalls.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) +
            (if (id.asKnown().isPresent) 1 else 0) +
            (contentParts.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0)

    /** Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation). */
    @JsonDeserialize(using = ContentPart.Deserializer::class)
    @JsonSerialize(using = ContentPart.Serializer::class)
    class ContentPart
    private constructor(
        private val chatCompletionContentPartText: ChatCompletionContentPartText? = null,
        private val chatCompletionContentPartImage: ChatCompletionContentPartImage? = null,
        private val _json: JsonValue? = null,
    ) {

        /** Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation). */
        fun chatCompletionContentPartText(): Optional<ChatCompletionContentPartText> =
            Optional.ofNullable(chatCompletionContentPartText)

        /** Learn about [image inputs](https://platform.openai.com/docs/guides/vision). */
        fun chatCompletionContentPartImage(): Optional<ChatCompletionContentPartImage> =
            Optional.ofNullable(chatCompletionContentPartImage)

        fun isChatCompletionContentPartText(): Boolean = chatCompletionContentPartText != null

        fun isChatCompletionContentPartImage(): Boolean = chatCompletionContentPartImage != null

        /** Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation). */
        fun asChatCompletionContentPartText(): ChatCompletionContentPartText =
            chatCompletionContentPartText.getOrThrow("chatCompletionContentPartText")

        /** Learn about [image inputs](https://platform.openai.com/docs/guides/vision). */
        fun asChatCompletionContentPartImage(): ChatCompletionContentPartImage =
            chatCompletionContentPartImage.getOrThrow("chatCompletionContentPartImage")

        fun _json(): Optional<JsonValue> = Optional.ofNullable(_json)

        fun <T> accept(visitor: Visitor<T>): T =
            when {
                chatCompletionContentPartText != null ->
                    visitor.visitChatCompletionContentPartText(chatCompletionContentPartText)
                chatCompletionContentPartImage != null ->
                    visitor.visitChatCompletionContentPartImage(chatCompletionContentPartImage)
                else -> visitor.unknown(_json)
            }

        private var validated: Boolean = false

        fun validate(): ContentPart = apply {
            if (validated) {
                return@apply
            }

            accept(
                object : Visitor<Unit> {
                    override fun visitChatCompletionContentPartText(
                        chatCompletionContentPartText: ChatCompletionContentPartText
                    ) {
                        chatCompletionContentPartText.validate()
                    }

                    override fun visitChatCompletionContentPartImage(
                        chatCompletionContentPartImage: ChatCompletionContentPartImage
                    ) {
                        chatCompletionContentPartImage.validate()
                    }
                }
            )
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            accept(
                object : Visitor<Int> {
                    override fun visitChatCompletionContentPartText(
                        chatCompletionContentPartText: ChatCompletionContentPartText
                    ) = chatCompletionContentPartText.validity()

                    override fun visitChatCompletionContentPartImage(
                        chatCompletionContentPartImage: ChatCompletionContentPartImage
                    ) = chatCompletionContentPartImage.validity()

                    override fun unknown(json: JsonValue?) = 0
                }
            )

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is ContentPart &&
                chatCompletionContentPartText == other.chatCompletionContentPartText &&
                chatCompletionContentPartImage == other.chatCompletionContentPartImage
        }

        override fun hashCode(): Int =
            Objects.hash(chatCompletionContentPartText, chatCompletionContentPartImage)

        override fun toString(): String =
            when {
                chatCompletionContentPartText != null ->
                    "ContentPart{chatCompletionContentPartText=$chatCompletionContentPartText}"
                chatCompletionContentPartImage != null ->
                    "ContentPart{chatCompletionContentPartImage=$chatCompletionContentPartImage}"
                _json != null -> "ContentPart{_unknown=$_json}"
                else -> throw IllegalStateException("Invalid ContentPart")
            }

        companion object {

            /**
             * Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation).
             */
            @JvmStatic
            fun ofChatCompletionContentPartText(
                chatCompletionContentPartText: ChatCompletionContentPartText
            ) = ContentPart(chatCompletionContentPartText = chatCompletionContentPartText)

            /** Learn about [image inputs](https://platform.openai.com/docs/guides/vision). */
            @JvmStatic
            fun ofChatCompletionContentPartImage(
                chatCompletionContentPartImage: ChatCompletionContentPartImage
            ) = ContentPart(chatCompletionContentPartImage = chatCompletionContentPartImage)
        }

        /**
         * An interface that defines how to map each variant of [ContentPart] to a value of type
         * [T].
         */
        interface Visitor<out T> {

            /**
             * Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation).
             */
            fun visitChatCompletionContentPartText(
                chatCompletionContentPartText: ChatCompletionContentPartText
            ): T

            /** Learn about [image inputs](https://platform.openai.com/docs/guides/vision). */
            fun visitChatCompletionContentPartImage(
                chatCompletionContentPartImage: ChatCompletionContentPartImage
            ): T

            /**
             * Maps an unknown variant of [ContentPart] to a value of type [T].
             *
             * An instance of [ContentPart] can contain an unknown variant if it was deserialized
             * from data that doesn't match any known variant. For example, if the SDK is on an
             * older version than the API, then the API may respond with new variants that the SDK
             * is unaware of.
             *
             * @throws OpenAIInvalidDataException in the default implementation.
             */
            fun unknown(json: JsonValue?): T {
                throw OpenAIInvalidDataException("Unknown ContentPart: $json")
            }
        }

        internal class Deserializer : BaseDeserializer<ContentPart>(ContentPart::class) {

            override fun ObjectCodec.deserialize(node: JsonNode): ContentPart {
                val json = JsonValue.fromJsonNode(node)

                val bestMatches =
                    sequenceOf(
                            tryDeserialize(node, jacksonTypeRef<ChatCompletionContentPartText>())
                                ?.let {
                                    ContentPart(chatCompletionContentPartText = it, _json = json)
                                },
                            tryDeserialize(node, jacksonTypeRef<ChatCompletionContentPartImage>())
                                ?.let {
                                    ContentPart(chatCompletionContentPartImage = it, _json = json)
                                },
                        )
                        .filterNotNull()
                        .allMaxBy { it.validity() }
                        .toList()
                return when (bestMatches.size) {
                    // This can happen if what we're deserializing is completely incompatible with
                    // all the possible variants (e.g. deserializing from boolean).
                    0 -> ContentPart(_json = json)
                    1 -> bestMatches.single()
                    // If there's more than one match with the highest validity, then use the first
                    // completely valid match, or simply the first match if none are completely
                    // valid.
                    else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first()
                }
            }
        }

        internal class Serializer : BaseSerializer<ContentPart>(ContentPart::class) {

            override fun serialize(
                value: ContentPart,
                generator: JsonGenerator,
                provider: SerializerProvider,
            ) {
                when {
                    value.chatCompletionContentPartText != null ->
                        generator.writeObject(value.chatCompletionContentPartText)
                    value.chatCompletionContentPartImage != null ->
                        generator.writeObject(value.chatCompletionContentPartImage)
                    value._json != null -> generator.writeObject(value._json)
                    else -> throw IllegalStateException("Invalid ContentPart")
                }
            }
        }
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) {
            return true
        }

        return other is ChatCompletionStoreMessage &&
            content == other.content &&
            refusal == other.refusal &&
            role == other.role &&
            annotations == other.annotations &&
            audio == other.audio &&
            functionCall == other.functionCall &&
            toolCalls == other.toolCalls &&
            id == other.id &&
            contentParts == other.contentParts &&
            additionalProperties == other.additionalProperties
    }

    private val hashCode: Int by lazy {
        Objects.hash(
            content,
            refusal,
            role,
            annotations,
            audio,
            functionCall,
            toolCalls,
            id,
            contentParts,
            additionalProperties,
        )
    }

    override fun hashCode(): Int = hashCode

    override fun toString() =
        "ChatCompletionStoreMessage{content=$content, refusal=$refusal, role=$role, annotations=$annotations, audio=$audio, functionCall=$functionCall, toolCalls=$toolCalls, id=$id, contentParts=$contentParts, additionalProperties=$additionalProperties}"
}
