// File generated from our OpenAPI spec by Stainless.

package com.openai.models.responses

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.Enum
import com.openai.core.ExcludeMissing
import com.openai.core.JsonField
import com.openai.core.JsonMissing
import com.openai.core.JsonValue
import com.openai.core.NoAutoDetect
import com.openai.core.checkRequired
import com.openai.core.getOrThrow
import com.openai.core.immutableEmptyMap
import com.openai.core.toImmutable
import com.openai.errors.OpenAIInvalidDataException
import java.util.Objects
import java.util.Optional

/**
 * A message input to the model with a role indicating instruction following hierarchy. Instructions
 * given with the `developer` or `system` role take precedence over instructions given with the
 * `user` role. Messages with the `assistant` role are presumed to have been generated by the model
 * in previous interactions.
 */
@NoAutoDetect
class EasyInputMessage
@JsonCreator
private constructor(
    @JsonProperty("content")
    @ExcludeMissing
    private val content: JsonField<Content> = JsonMissing.of(),
    @JsonProperty("role") @ExcludeMissing private val role: JsonField<Role> = JsonMissing.of(),
    @JsonProperty("type") @ExcludeMissing private val type: JsonField<Type> = JsonMissing.of(),
    @JsonAnySetter private val additionalProperties: Map<String, JsonValue> = immutableEmptyMap(),
) {

    /**
     * Text, image, or audio input to the model, used to generate a response. Can also contain
     * previous assistant responses.
     */
    fun content(): Content = content.getRequired("content")

    /** The role of the message input. One of `user`, `assistant`, `system`, or `developer`. */
    fun role(): Role = role.getRequired("role")

    /** The type of the message input. Always `message`. */
    fun type(): Optional<Type> = Optional.ofNullable(type.getNullable("type"))

    /**
     * Text, image, or audio input to the model, used to generate a response. Can also contain
     * previous assistant responses.
     */
    @JsonProperty("content") @ExcludeMissing fun _content(): JsonField<Content> = content

    /** The role of the message input. One of `user`, `assistant`, `system`, or `developer`. */
    @JsonProperty("role") @ExcludeMissing fun _role(): JsonField<Role> = role

    /** The type of the message input. Always `message`. */
    @JsonProperty("type") @ExcludeMissing fun _type(): JsonField<Type> = type

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

    private var validated: Boolean = false

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

        content().validate()
        role()
        type()
        validated = true
    }

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

    companion object {

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

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

        private var content: JsonField<Content>? = null
        private var role: JsonField<Role>? = null
        private var type: JsonField<Type> = JsonMissing.of()
        private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

        @JvmSynthetic
        internal fun from(easyInputMessage: EasyInputMessage) = apply {
            content = easyInputMessage.content
            role = easyInputMessage.role
            type = easyInputMessage.type
            additionalProperties = easyInputMessage.additionalProperties.toMutableMap()
        }

        /**
         * Text, image, or audio input to the model, used to generate a response. Can also contain
         * previous assistant responses.
         */
        fun content(content: Content) = content(JsonField.of(content))

        /**
         * Text, image, or audio input to the model, used to generate a response. Can also contain
         * previous assistant responses.
         */
        fun content(content: JsonField<Content>) = apply { this.content = content }

        /** A text input to the model. */
        fun content(textInput: String) = content(Content.ofTextInput(textInput))

        /** A list of one or many input items to the model, containing different content types. */
        fun contentOfResponseInputMessageContentList(
            responseInputMessageContentList: List<ResponseInputContent>
        ) = content(Content.ofResponseInputMessageContentList(responseInputMessageContentList))

        /** The role of the message input. One of `user`, `assistant`, `system`, or `developer`. */
        fun role(role: Role) = role(JsonField.of(role))

        /** The role of the message input. One of `user`, `assistant`, `system`, or `developer`. */
        fun role(role: JsonField<Role>) = apply { this.role = role }

        /** The type of the message input. Always `message`. */
        fun type(type: Type) = type(JsonField.of(type))

        /** The type of the message input. Always `message`. */
        fun type(type: JsonField<Type>) = apply { this.type = type }

        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)
        }

        fun build(): EasyInputMessage =
            EasyInputMessage(
                checkRequired("content", content),
                checkRequired("role", role),
                type,
                additionalProperties.toImmutable(),
            )
    }

    /**
     * Text, image, or audio input to the model, used to generate a response. Can also contain
     * previous assistant responses.
     */
    @JsonDeserialize(using = Content.Deserializer::class)
    @JsonSerialize(using = Content.Serializer::class)
    class Content
    private constructor(
        private val textInput: String? = null,
        private val responseInputMessageContentList: List<ResponseInputContent>? = null,
        private val _json: JsonValue? = null,
    ) {

        /** A text input to the model. */
        fun textInput(): Optional<String> = Optional.ofNullable(textInput)

        /** A list of one or many input items to the model, containing different content types. */
        fun responseInputMessageContentList(): Optional<List<ResponseInputContent>> =
            Optional.ofNullable(responseInputMessageContentList)

        fun isTextInput(): Boolean = textInput != null

        fun isResponseInputMessageContentList(): Boolean = responseInputMessageContentList != null

        /** A text input to the model. */
        fun asTextInput(): String = textInput.getOrThrow("textInput")

        /** A list of one or many input items to the model, containing different content types. */
        fun asResponseInputMessageContentList(): List<ResponseInputContent> =
            responseInputMessageContentList.getOrThrow("responseInputMessageContentList")

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

        fun <T> accept(visitor: Visitor<T>): T {
            return when {
                textInput != null -> visitor.visitTextInput(textInput)
                responseInputMessageContentList != null ->
                    visitor.visitResponseInputMessageContentList(responseInputMessageContentList)
                else -> visitor.unknown(_json)
            }
        }

        private var validated: Boolean = false

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

            accept(
                object : Visitor<Unit> {
                    override fun visitTextInput(textInput: String) {}

                    override fun visitResponseInputMessageContentList(
                        responseInputMessageContentList: List<ResponseInputContent>
                    ) {
                        responseInputMessageContentList.forEach { it.validate() }
                    }
                }
            )
            validated = true
        }

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

            return /* spotless:off */ other is Content && textInput == other.textInput && responseInputMessageContentList == other.responseInputMessageContentList /* spotless:on */
        }

        override fun hashCode(): Int = /* spotless:off */ Objects.hash(textInput, responseInputMessageContentList) /* spotless:on */

        override fun toString(): String =
            when {
                textInput != null -> "Content{textInput=$textInput}"
                responseInputMessageContentList != null ->
                    "Content{responseInputMessageContentList=$responseInputMessageContentList}"
                _json != null -> "Content{_unknown=$_json}"
                else -> throw IllegalStateException("Invalid Content")
            }

        companion object {

            /** A text input to the model. */
            @JvmStatic fun ofTextInput(textInput: String) = Content(textInput = textInput)

            /**
             * A list of one or many input items to the model, containing different content types.
             */
            @JvmStatic
            fun ofResponseInputMessageContentList(
                responseInputMessageContentList: List<ResponseInputContent>
            ) = Content(responseInputMessageContentList = responseInputMessageContentList)
        }

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

            /** A text input to the model. */
            fun visitTextInput(textInput: String): T

            /**
             * A list of one or many input items to the model, containing different content types.
             */
            fun visitResponseInputMessageContentList(
                responseInputMessageContentList: List<ResponseInputContent>
            ): T

            /**
             * Maps an unknown variant of [Content] to a value of type [T].
             *
             * An instance of [Content] 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 Content: $json")
            }
        }

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

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

                tryDeserialize(node, jacksonTypeRef<String>())?.let {
                    return Content(textInput = it, _json = json)
                }
                tryDeserialize(node, jacksonTypeRef<List<ResponseInputContent>>()) {
                        it.forEach { it.validate() }
                    }
                    ?.let {
                        return Content(responseInputMessageContentList = it, _json = json)
                    }

                return Content(_json = json)
            }
        }

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

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

    /** The role of the message input. One of `user`, `assistant`, `system`, or `developer`. */
    class Role @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

        /**
         * Returns this class instance's raw value.
         *
         * This is usually only useful if this instance was deserialized from data that doesn't
         * match any known member, and you want to know that value. For example, if the SDK is on an
         * older version than the API, then the API may respond with new members that the SDK is
         * unaware of.
         */
        @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

        companion object {

            @JvmField val USER = of("user")

            @JvmField val ASSISTANT = of("assistant")

            @JvmField val SYSTEM = of("system")

            @JvmField val DEVELOPER = of("developer")

            @JvmStatic fun of(value: String) = Role(JsonField.of(value))
        }

        /** An enum containing [Role]'s known values. */
        enum class Known {
            USER,
            ASSISTANT,
            SYSTEM,
            DEVELOPER,
        }

        /**
         * An enum containing [Role]'s known values, as well as an [_UNKNOWN] member.
         *
         * An instance of [Role] can contain an unknown value in a couple of cases:
         * - It was deserialized from data that doesn't match any known member. For example, if the
         *   SDK is on an older version than the API, then the API may respond with new members that
         *   the SDK is unaware of.
         * - It was constructed with an arbitrary value using the [of] method.
         */
        enum class Value {
            USER,
            ASSISTANT,
            SYSTEM,
            DEVELOPER,
            /** An enum member indicating that [Role] was instantiated with an unknown value. */
            _UNKNOWN,
        }

        /**
         * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN]
         * if the class was instantiated with an unknown value.
         *
         * Use the [known] method instead if you're certain the value is always known or if you want
         * to throw for the unknown case.
         */
        fun value(): Value =
            when (this) {
                USER -> Value.USER
                ASSISTANT -> Value.ASSISTANT
                SYSTEM -> Value.SYSTEM
                DEVELOPER -> Value.DEVELOPER
                else -> Value._UNKNOWN
            }

        /**
         * Returns an enum member corresponding to this class instance's value.
         *
         * Use the [value] method instead if you're uncertain the value is always known and don't
         * want to throw for the unknown case.
         *
         * @throws OpenAIInvalidDataException if this class instance's value is a not a known
         *   member.
         */
        fun known(): Known =
            when (this) {
                USER -> Known.USER
                ASSISTANT -> Known.ASSISTANT
                SYSTEM -> Known.SYSTEM
                DEVELOPER -> Known.DEVELOPER
                else -> throw OpenAIInvalidDataException("Unknown Role: $value")
            }

        /**
         * Returns this class instance's primitive wire representation.
         *
         * This differs from the [toString] method because that method is primarily for debugging
         * and generally doesn't throw.
         *
         * @throws OpenAIInvalidDataException if this class instance's value does not have the
         *   expected primitive type.
         */
        fun asString(): String =
            _value().asString().orElseThrow { OpenAIInvalidDataException("Value is not a String") }

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

            return /* spotless:off */ other is Role && value == other.value /* spotless:on */
        }

        override fun hashCode() = value.hashCode()

        override fun toString() = value.toString()
    }

    /** The type of the message input. Always `message`. */
    class Type @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

        /**
         * Returns this class instance's raw value.
         *
         * This is usually only useful if this instance was deserialized from data that doesn't
         * match any known member, and you want to know that value. For example, if the SDK is on an
         * older version than the API, then the API may respond with new members that the SDK is
         * unaware of.
         */
        @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

        companion object {

            @JvmField val MESSAGE = of("message")

            @JvmStatic fun of(value: String) = Type(JsonField.of(value))
        }

        /** An enum containing [Type]'s known values. */
        enum class Known {
            MESSAGE
        }

        /**
         * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member.
         *
         * An instance of [Type] can contain an unknown value in a couple of cases:
         * - It was deserialized from data that doesn't match any known member. For example, if the
         *   SDK is on an older version than the API, then the API may respond with new members that
         *   the SDK is unaware of.
         * - It was constructed with an arbitrary value using the [of] method.
         */
        enum class Value {
            MESSAGE,
            /** An enum member indicating that [Type] was instantiated with an unknown value. */
            _UNKNOWN,
        }

        /**
         * Returns an enum member corresponding to this class instance's value, or [Value._UNKNOWN]
         * if the class was instantiated with an unknown value.
         *
         * Use the [known] method instead if you're certain the value is always known or if you want
         * to throw for the unknown case.
         */
        fun value(): Value =
            when (this) {
                MESSAGE -> Value.MESSAGE
                else -> Value._UNKNOWN
            }

        /**
         * Returns an enum member corresponding to this class instance's value.
         *
         * Use the [value] method instead if you're uncertain the value is always known and don't
         * want to throw for the unknown case.
         *
         * @throws OpenAIInvalidDataException if this class instance's value is a not a known
         *   member.
         */
        fun known(): Known =
            when (this) {
                MESSAGE -> Known.MESSAGE
                else -> throw OpenAIInvalidDataException("Unknown Type: $value")
            }

        /**
         * Returns this class instance's primitive wire representation.
         *
         * This differs from the [toString] method because that method is primarily for debugging
         * and generally doesn't throw.
         *
         * @throws OpenAIInvalidDataException if this class instance's value does not have the
         *   expected primitive type.
         */
        fun asString(): String =
            _value().asString().orElseThrow { OpenAIInvalidDataException("Value is not a String") }

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

            return /* spotless:off */ other is Type && value == other.value /* spotless:on */
        }

        override fun hashCode() = value.hashCode()

        override fun toString() = value.toString()
    }

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

        return /* spotless:off */ other is EasyInputMessage && content == other.content && role == other.role && type == other.type && additionalProperties == other.additionalProperties /* spotless:on */
    }

    /* spotless:off */
    private val hashCode: Int by lazy { Objects.hash(content, role, type, additionalProperties) }
    /* spotless:on */

    override fun hashCode(): Int = hashCode

    override fun toString() =
        "EasyInputMessage{content=$content, role=$role, type=$type, additionalProperties=$additionalProperties}"
}
