// 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.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.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

/** The output of a custom tool call from your code, being sent back to the model. */
class ResponseCustomToolCallOutput
@JsonCreator(mode = JsonCreator.Mode.DISABLED)
private constructor(
    private val callId: JsonField<String>,
    private val output: JsonField<Output>,
    private val type: JsonValue,
    private val id: JsonField<String>,
    private val additionalProperties: MutableMap<String, JsonValue>,
) {

    @JsonCreator
    private constructor(
        @JsonProperty("call_id") @ExcludeMissing callId: JsonField<String> = JsonMissing.of(),
        @JsonProperty("output") @ExcludeMissing output: JsonField<Output> = JsonMissing.of(),
        @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
        @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
    ) : this(callId, output, type, id, mutableMapOf())

    /**
     * The call ID, used to map this custom tool call output to a custom tool call.
     *
     * @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 callId(): String = callId.getRequired("call_id")

    /**
     * The output from the custom tool call generated by your code. Can be a string or an list of
     * output content.
     *
     * @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 output(): Output = output.getRequired("output")

    /**
     * The type of the custom tool call output. Always `custom_tool_call_output`.
     *
     * Expected to always return the following:
     * ```java
     * JsonValue.from("custom_tool_call_output")
     * ```
     *
     * However, this method can be useful for debugging and logging (e.g. if the server responded
     * with an unexpected value).
     */
    @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

    /**
     * The unique ID of the custom tool call output in the OpenAI platform.
     *
     * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
     *   server responded with an unexpected value).
     */
    fun id(): Optional<String> = id.getOptional("id")

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

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

    /**
     * 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

    @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 [ResponseCustomToolCallOutput].
         *
         * The following fields are required:
         * ```java
         * .callId()
         * .output()
         * ```
         */
        @JvmStatic fun builder() = Builder()
    }

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

        private var callId: JsonField<String>? = null
        private var output: JsonField<Output>? = null
        private var type: JsonValue = JsonValue.from("custom_tool_call_output")
        private var id: JsonField<String> = JsonMissing.of()
        private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

        @JvmSynthetic
        internal fun from(responseCustomToolCallOutput: ResponseCustomToolCallOutput) = apply {
            callId = responseCustomToolCallOutput.callId
            output = responseCustomToolCallOutput.output
            type = responseCustomToolCallOutput.type
            id = responseCustomToolCallOutput.id
            additionalProperties = responseCustomToolCallOutput.additionalProperties.toMutableMap()
        }

        /** The call ID, used to map this custom tool call output to a custom tool call. */
        fun callId(callId: String) = callId(JsonField.of(callId))

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

        /**
         * The output from the custom tool call generated by your code. Can be a string or an list
         * of output content.
         */
        fun output(output: Output) = output(JsonField.of(output))

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

        /** Alias for calling [output] with `Output.ofString(string)`. */
        fun output(string: String) = output(Output.ofString(string))

        /** Alias for calling [output] with `Output.ofContentList(contentList)`. */
        fun outputOfContentList(contentList: List<Output.FunctionAndCustomToolCallOutput>) =
            output(Output.ofContentList(contentList))

        /**
         * 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("custom_tool_call_output")
         * ```
         *
         * This method is primarily for setting the field to an undocumented or not yet supported
         * value.
         */
        fun type(type: JsonValue) = apply { this.type = type }

        /** The unique ID of the custom tool call output in the OpenAI platform. */
        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 }

        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 [ResponseCustomToolCallOutput].
         *
         * Further updates to this [Builder] will not mutate the returned instance.
         *
         * The following fields are required:
         * ```java
         * .callId()
         * .output()
         * ```
         *
         * @throws IllegalStateException if any required field is unset.
         */
        fun build(): ResponseCustomToolCallOutput =
            ResponseCustomToolCallOutput(
                checkRequired("callId", callId),
                checkRequired("output", output),
                type,
                id,
                additionalProperties.toMutableMap(),
            )
    }

    private var validated: Boolean = false

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

        callId()
        output().validate()
        _type().let {
            if (it != JsonValue.from("custom_tool_call_output")) {
                throw OpenAIInvalidDataException("'type' is invalid, received $it")
            }
        }
        id()
        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 (callId.asKnown().isPresent) 1 else 0) +
            (output.asKnown().getOrNull()?.validity() ?: 0) +
            type.let { if (it == JsonValue.from("custom_tool_call_output")) 1 else 0 } +
            (if (id.asKnown().isPresent) 1 else 0)

    /**
     * The output from the custom tool call generated by your code. Can be a string or an list of
     * output content.
     */
    @JsonDeserialize(using = Output.Deserializer::class)
    @JsonSerialize(using = Output.Serializer::class)
    class Output
    private constructor(
        private val string: String? = null,
        private val contentList: List<FunctionAndCustomToolCallOutput>? = null,
        private val _json: JsonValue? = null,
    ) {

        /** A string of the output of the custom tool call. */
        fun string(): Optional<String> = Optional.ofNullable(string)

        /** Text, image, or file output of the custom tool call. */
        fun contentList(): Optional<List<FunctionAndCustomToolCallOutput>> =
            Optional.ofNullable(contentList)

        fun isString(): Boolean = string != null

        fun isContentList(): Boolean = contentList != null

        /** A string of the output of the custom tool call. */
        fun asString(): String = string.getOrThrow("string")

        /** Text, image, or file output of the custom tool call. */
        fun asContentList(): List<FunctionAndCustomToolCallOutput> =
            contentList.getOrThrow("contentList")

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

        fun <T> accept(visitor: Visitor<T>): T =
            when {
                string != null -> visitor.visitString(string)
                contentList != null -> visitor.visitContentList(contentList)
                else -> visitor.unknown(_json)
            }

        private var validated: Boolean = false

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

            accept(
                object : Visitor<Unit> {
                    override fun visitString(string: String) {}

                    override fun visitContentList(
                        contentList: List<FunctionAndCustomToolCallOutput>
                    ) {
                        contentList.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 =
            accept(
                object : Visitor<Int> {
                    override fun visitString(string: String) = 1

                    override fun visitContentList(
                        contentList: List<FunctionAndCustomToolCallOutput>
                    ) = contentList.sumOf { it.validity().toInt() }

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

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

            return other is Output && string == other.string && contentList == other.contentList
        }

        override fun hashCode(): Int = Objects.hash(string, contentList)

        override fun toString(): String =
            when {
                string != null -> "Output{string=$string}"
                contentList != null -> "Output{contentList=$contentList}"
                _json != null -> "Output{_unknown=$_json}"
                else -> throw IllegalStateException("Invalid Output")
            }

        companion object {

            /** A string of the output of the custom tool call. */
            @JvmStatic fun ofString(string: String) = Output(string = string)

            /** Text, image, or file output of the custom tool call. */
            @JvmStatic
            fun ofContentList(contentList: List<FunctionAndCustomToolCallOutput>) =
                Output(contentList = contentList.toImmutable())
        }

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

            /** A string of the output of the custom tool call. */
            fun visitString(string: String): T

            /** Text, image, or file output of the custom tool call. */
            fun visitContentList(contentList: List<FunctionAndCustomToolCallOutput>): T

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

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

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

                val bestMatches =
                    sequenceOf(
                            tryDeserialize(node, jacksonTypeRef<String>())?.let {
                                Output(string = it, _json = json)
                            },
                            tryDeserialize(
                                    node,
                                    jacksonTypeRef<List<FunctionAndCustomToolCallOutput>>(),
                                )
                                ?.let { Output(contentList = 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 object).
                    0 -> Output(_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<Output>(Output::class) {

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

        /** A text input to the model. */
        @JsonDeserialize(using = FunctionAndCustomToolCallOutput.Deserializer::class)
        @JsonSerialize(using = FunctionAndCustomToolCallOutput.Serializer::class)
        class FunctionAndCustomToolCallOutput
        private constructor(
            private val inputText: ResponseInputText? = null,
            private val inputImage: ResponseInputImage? = null,
            private val inputFile: ResponseInputFile? = null,
            private val _json: JsonValue? = null,
        ) {

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

            /**
             * An image input to the model. Learn about
             * [image inputs](https://platform.openai.com/docs/guides/vision).
             */
            fun inputImage(): Optional<ResponseInputImage> = Optional.ofNullable(inputImage)

            /** A file input to the model. */
            fun inputFile(): Optional<ResponseInputFile> = Optional.ofNullable(inputFile)

            fun isInputText(): Boolean = inputText != null

            fun isInputImage(): Boolean = inputImage != null

            fun isInputFile(): Boolean = inputFile != null

            /** A text input to the model. */
            fun asInputText(): ResponseInputText = inputText.getOrThrow("inputText")

            /**
             * An image input to the model. Learn about
             * [image inputs](https://platform.openai.com/docs/guides/vision).
             */
            fun asInputImage(): ResponseInputImage = inputImage.getOrThrow("inputImage")

            /** A file input to the model. */
            fun asInputFile(): ResponseInputFile = inputFile.getOrThrow("inputFile")

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

            fun <T> accept(visitor: Visitor<T>): T =
                when {
                    inputText != null -> visitor.visitInputText(inputText)
                    inputImage != null -> visitor.visitInputImage(inputImage)
                    inputFile != null -> visitor.visitInputFile(inputFile)
                    else -> visitor.unknown(_json)
                }

            private var validated: Boolean = false

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

                accept(
                    object : Visitor<Unit> {
                        override fun visitInputText(inputText: ResponseInputText) {
                            inputText.validate()
                        }

                        override fun visitInputImage(inputImage: ResponseInputImage) {
                            inputImage.validate()
                        }

                        override fun visitInputFile(inputFile: ResponseInputFile) {
                            inputFile.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 visitInputText(inputText: ResponseInputText) =
                            inputText.validity()

                        override fun visitInputImage(inputImage: ResponseInputImage) =
                            inputImage.validity()

                        override fun visitInputFile(inputFile: ResponseInputFile) =
                            inputFile.validity()

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

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

                return other is FunctionAndCustomToolCallOutput &&
                    inputText == other.inputText &&
                    inputImage == other.inputImage &&
                    inputFile == other.inputFile
            }

            override fun hashCode(): Int = Objects.hash(inputText, inputImage, inputFile)

            override fun toString(): String =
                when {
                    inputText != null -> "FunctionAndCustomToolCallOutput{inputText=$inputText}"
                    inputImage != null -> "FunctionAndCustomToolCallOutput{inputImage=$inputImage}"
                    inputFile != null -> "FunctionAndCustomToolCallOutput{inputFile=$inputFile}"
                    _json != null -> "FunctionAndCustomToolCallOutput{_unknown=$_json}"
                    else -> throw IllegalStateException("Invalid FunctionAndCustomToolCallOutput")
                }

            companion object {

                /** A text input to the model. */
                @JvmStatic
                fun ofInputText(inputText: ResponseInputText) =
                    FunctionAndCustomToolCallOutput(inputText = inputText)

                /**
                 * An image input to the model. Learn about
                 * [image inputs](https://platform.openai.com/docs/guides/vision).
                 */
                @JvmStatic
                fun ofInputImage(inputImage: ResponseInputImage) =
                    FunctionAndCustomToolCallOutput(inputImage = inputImage)

                /** A file input to the model. */
                @JvmStatic
                fun ofInputFile(inputFile: ResponseInputFile) =
                    FunctionAndCustomToolCallOutput(inputFile = inputFile)
            }

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

                /** A text input to the model. */
                fun visitInputText(inputText: ResponseInputText): T

                /**
                 * An image input to the model. Learn about
                 * [image inputs](https://platform.openai.com/docs/guides/vision).
                 */
                fun visitInputImage(inputImage: ResponseInputImage): T

                /** A file input to the model. */
                fun visitInputFile(inputFile: ResponseInputFile): T

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

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

                override fun ObjectCodec.deserialize(
                    node: JsonNode
                ): FunctionAndCustomToolCallOutput {
                    val json = JsonValue.fromJsonNode(node)
                    val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull()

                    when (type) {
                        "input_text" -> {
                            return tryDeserialize(node, jacksonTypeRef<ResponseInputText>())?.let {
                                FunctionAndCustomToolCallOutput(inputText = it, _json = json)
                            } ?: FunctionAndCustomToolCallOutput(_json = json)
                        }
                        "input_image" -> {
                            return tryDeserialize(node, jacksonTypeRef<ResponseInputImage>())?.let {
                                FunctionAndCustomToolCallOutput(inputImage = it, _json = json)
                            } ?: FunctionAndCustomToolCallOutput(_json = json)
                        }
                        "input_file" -> {
                            return tryDeserialize(node, jacksonTypeRef<ResponseInputFile>())?.let {
                                FunctionAndCustomToolCallOutput(inputFile = it, _json = json)
                            } ?: FunctionAndCustomToolCallOutput(_json = json)
                        }
                    }

                    return FunctionAndCustomToolCallOutput(_json = json)
                }
            }

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

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

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

        return other is ResponseCustomToolCallOutput &&
            callId == other.callId &&
            output == other.output &&
            type == other.type &&
            id == other.id &&
            additionalProperties == other.additionalProperties
    }

    private val hashCode: Int by lazy {
        Objects.hash(callId, output, type, id, additionalProperties)
    }

    override fun hashCode(): Int = hashCode

    override fun toString() =
        "ResponseCustomToolCallOutput{callId=$callId, output=$output, type=$type, id=$id, additionalProperties=$additionalProperties}"
}
