// 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.checkRequired
import com.openai.core.getOrThrow
import com.openai.errors.OpenAIInvalidDataException
import java.util.Collections
import java.util.Objects
import java.util.Optional
import kotlin.jvm.optionals.getOrNull

/** A tool call that applies file diffs by creating, deleting, or updating files. */
class ResponseApplyPatchToolCall
@JsonCreator(mode = JsonCreator.Mode.DISABLED)
private constructor(
    private val id: JsonField<String>,
    private val callId: JsonField<String>,
    private val operation: JsonField<Operation>,
    private val status: JsonField<Status>,
    private val type: JsonValue,
    private val createdBy: JsonField<String>,
    private val additionalProperties: MutableMap<String, JsonValue>,
) {

    @JsonCreator
    private constructor(
        @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
        @JsonProperty("call_id") @ExcludeMissing callId: JsonField<String> = JsonMissing.of(),
        @JsonProperty("operation")
        @ExcludeMissing
        operation: JsonField<Operation> = JsonMissing.of(),
        @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
        @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
        @JsonProperty("created_by") @ExcludeMissing createdBy: JsonField<String> = JsonMissing.of(),
    ) : this(id, callId, operation, status, type, createdBy, mutableMapOf())

    /**
     * The unique ID of the apply patch tool call. Populated when this item is returned via API.
     *
     * @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")

    /**
     * The unique ID of the apply patch tool call generated by the model.
     *
     * @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")

    /**
     * One of the create_file, delete_file, or update_file operations applied via apply_patch.
     *
     * @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 operation(): Operation = operation.getRequired("operation")

    /**
     * The status of the apply patch tool call. One of `in_progress` or `completed`.
     *
     * @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 status(): Status = status.getRequired("status")

    /**
     * The type of the item. Always `apply_patch_call`.
     *
     * Expected to always return the following:
     * ```java
     * JsonValue.from("apply_patch_call")
     * ```
     *
     * 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 ID of the entity that created this tool call.
     *
     * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
     *   server responded with an unexpected value).
     */
    fun createdBy(): Optional<String> = createdBy.getOptional("created_by")

    /**
     * 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 [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 [operation].
     *
     * Unlike [operation], this method doesn't throw if the JSON field has an unexpected type.
     */
    @JsonProperty("operation") @ExcludeMissing fun _operation(): JsonField<Operation> = operation

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

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

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

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

        private var id: JsonField<String>? = null
        private var callId: JsonField<String>? = null
        private var operation: JsonField<Operation>? = null
        private var status: JsonField<Status>? = null
        private var type: JsonValue = JsonValue.from("apply_patch_call")
        private var createdBy: JsonField<String> = JsonMissing.of()
        private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

        @JvmSynthetic
        internal fun from(responseApplyPatchToolCall: ResponseApplyPatchToolCall) = apply {
            id = responseApplyPatchToolCall.id
            callId = responseApplyPatchToolCall.callId
            operation = responseApplyPatchToolCall.operation
            status = responseApplyPatchToolCall.status
            type = responseApplyPatchToolCall.type
            createdBy = responseApplyPatchToolCall.createdBy
            additionalProperties = responseApplyPatchToolCall.additionalProperties.toMutableMap()
        }

        /**
         * The unique ID of the apply patch tool call. Populated when this item is returned via API.
         */
        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 }

        /** The unique ID of the apply patch tool call generated by the model. */
        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 }

        /**
         * One of the create_file, delete_file, or update_file operations applied via apply_patch.
         */
        fun operation(operation: Operation) = operation(JsonField.of(operation))

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

        /** Alias for calling [operation] with `Operation.ofCreateFile(createFile)`. */
        fun operation(createFile: Operation.CreateFile) =
            operation(Operation.ofCreateFile(createFile))

        /** Alias for calling [operation] with `Operation.ofDeleteFile(deleteFile)`. */
        fun operation(deleteFile: Operation.DeleteFile) =
            operation(Operation.ofDeleteFile(deleteFile))

        /**
         * Alias for calling [operation] with the following:
         * ```java
         * Operation.DeleteFile.builder()
         *     .path(path)
         *     .build()
         * ```
         */
        fun deleteFileOperation(path: String) =
            operation(Operation.DeleteFile.builder().path(path).build())

        /** Alias for calling [operation] with `Operation.ofUpdateFile(updateFile)`. */
        fun operation(updateFile: Operation.UpdateFile) =
            operation(Operation.ofUpdateFile(updateFile))

        /** The status of the apply patch tool call. One of `in_progress` or `completed`. */
        fun status(status: Status) = status(JsonField.of(status))

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

        /**
         * 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("apply_patch_call")
         * ```
         *
         * 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 ID of the entity that created this tool call. */
        fun createdBy(createdBy: String) = createdBy(JsonField.of(createdBy))

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

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

    private var validated: Boolean = false

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

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

    /** One of the create_file, delete_file, or update_file operations applied via apply_patch. */
    @JsonDeserialize(using = Operation.Deserializer::class)
    @JsonSerialize(using = Operation.Serializer::class)
    class Operation
    private constructor(
        private val createFile: CreateFile? = null,
        private val deleteFile: DeleteFile? = null,
        private val updateFile: UpdateFile? = null,
        private val _json: JsonValue? = null,
    ) {

        /** Instruction describing how to create a file via the apply_patch tool. */
        fun createFile(): Optional<CreateFile> = Optional.ofNullable(createFile)

        /** Instruction describing how to delete a file via the apply_patch tool. */
        fun deleteFile(): Optional<DeleteFile> = Optional.ofNullable(deleteFile)

        /** Instruction describing how to update a file via the apply_patch tool. */
        fun updateFile(): Optional<UpdateFile> = Optional.ofNullable(updateFile)

        fun isCreateFile(): Boolean = createFile != null

        fun isDeleteFile(): Boolean = deleteFile != null

        fun isUpdateFile(): Boolean = updateFile != null

        /** Instruction describing how to create a file via the apply_patch tool. */
        fun asCreateFile(): CreateFile = createFile.getOrThrow("createFile")

        /** Instruction describing how to delete a file via the apply_patch tool. */
        fun asDeleteFile(): DeleteFile = deleteFile.getOrThrow("deleteFile")

        /** Instruction describing how to update a file via the apply_patch tool. */
        fun asUpdateFile(): UpdateFile = updateFile.getOrThrow("updateFile")

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

        fun <T> accept(visitor: Visitor<T>): T =
            when {
                createFile != null -> visitor.visitCreateFile(createFile)
                deleteFile != null -> visitor.visitDeleteFile(deleteFile)
                updateFile != null -> visitor.visitUpdateFile(updateFile)
                else -> visitor.unknown(_json)
            }

        private var validated: Boolean = false

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

            accept(
                object : Visitor<Unit> {
                    override fun visitCreateFile(createFile: CreateFile) {
                        createFile.validate()
                    }

                    override fun visitDeleteFile(deleteFile: DeleteFile) {
                        deleteFile.validate()
                    }

                    override fun visitUpdateFile(updateFile: UpdateFile) {
                        updateFile.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 visitCreateFile(createFile: CreateFile) = createFile.validity()

                    override fun visitDeleteFile(deleteFile: DeleteFile) = deleteFile.validity()

                    override fun visitUpdateFile(updateFile: UpdateFile) = updateFile.validity()

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

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

            return other is Operation &&
                createFile == other.createFile &&
                deleteFile == other.deleteFile &&
                updateFile == other.updateFile
        }

        override fun hashCode(): Int = Objects.hash(createFile, deleteFile, updateFile)

        override fun toString(): String =
            when {
                createFile != null -> "Operation{createFile=$createFile}"
                deleteFile != null -> "Operation{deleteFile=$deleteFile}"
                updateFile != null -> "Operation{updateFile=$updateFile}"
                _json != null -> "Operation{_unknown=$_json}"
                else -> throw IllegalStateException("Invalid Operation")
            }

        companion object {

            /** Instruction describing how to create a file via the apply_patch tool. */
            @JvmStatic fun ofCreateFile(createFile: CreateFile) = Operation(createFile = createFile)

            /** Instruction describing how to delete a file via the apply_patch tool. */
            @JvmStatic fun ofDeleteFile(deleteFile: DeleteFile) = Operation(deleteFile = deleteFile)

            /** Instruction describing how to update a file via the apply_patch tool. */
            @JvmStatic fun ofUpdateFile(updateFile: UpdateFile) = Operation(updateFile = updateFile)
        }

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

            /** Instruction describing how to create a file via the apply_patch tool. */
            fun visitCreateFile(createFile: CreateFile): T

            /** Instruction describing how to delete a file via the apply_patch tool. */
            fun visitDeleteFile(deleteFile: DeleteFile): T

            /** Instruction describing how to update a file via the apply_patch tool. */
            fun visitUpdateFile(updateFile: UpdateFile): T

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

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

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

                when (type) {
                    "create_file" -> {
                        return tryDeserialize(node, jacksonTypeRef<CreateFile>())?.let {
                            Operation(createFile = it, _json = json)
                        } ?: Operation(_json = json)
                    }
                    "delete_file" -> {
                        return tryDeserialize(node, jacksonTypeRef<DeleteFile>())?.let {
                            Operation(deleteFile = it, _json = json)
                        } ?: Operation(_json = json)
                    }
                    "update_file" -> {
                        return tryDeserialize(node, jacksonTypeRef<UpdateFile>())?.let {
                            Operation(updateFile = it, _json = json)
                        } ?: Operation(_json = json)
                    }
                }

                return Operation(_json = json)
            }
        }

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

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

        /** Instruction describing how to create a file via the apply_patch tool. */
        class CreateFile
        @JsonCreator(mode = JsonCreator.Mode.DISABLED)
        private constructor(
            private val diff: JsonField<String>,
            private val path: JsonField<String>,
            private val type: JsonValue,
            private val additionalProperties: MutableMap<String, JsonValue>,
        ) {

            @JsonCreator
            private constructor(
                @JsonProperty("diff") @ExcludeMissing diff: JsonField<String> = JsonMissing.of(),
                @JsonProperty("path") @ExcludeMissing path: JsonField<String> = JsonMissing.of(),
                @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            ) : this(diff, path, type, mutableMapOf())

            /**
             * Diff to apply.
             *
             * @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 diff(): String = diff.getRequired("diff")

            /**
             * Path of the file to create.
             *
             * @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 path(): String = path.getRequired("path")

            /**
             * Create a new file with the provided diff.
             *
             * Expected to always return the following:
             * ```java
             * JsonValue.from("create_file")
             * ```
             *
             * 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

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

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

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

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

                private var diff: JsonField<String>? = null
                private var path: JsonField<String>? = null
                private var type: JsonValue = JsonValue.from("create_file")
                private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

                @JvmSynthetic
                internal fun from(createFile: CreateFile) = apply {
                    diff = createFile.diff
                    path = createFile.path
                    type = createFile.type
                    additionalProperties = createFile.additionalProperties.toMutableMap()
                }

                /** Diff to apply. */
                fun diff(diff: String) = diff(JsonField.of(diff))

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

                /** Path of the file to create. */
                fun path(path: String) = path(JsonField.of(path))

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

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

                /**
                 * Returns an immutable instance of [CreateFile].
                 *
                 * Further updates to this [Builder] will not mutate the returned instance.
                 *
                 * The following fields are required:
                 * ```java
                 * .diff()
                 * .path()
                 * ```
                 *
                 * @throws IllegalStateException if any required field is unset.
                 */
                fun build(): CreateFile =
                    CreateFile(
                        checkRequired("diff", diff),
                        checkRequired("path", path),
                        type,
                        additionalProperties.toMutableMap(),
                    )
            }

            private var validated: Boolean = false

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

                diff()
                path()
                _type().let {
                    if (it != JsonValue.from("create_file")) {
                        throw OpenAIInvalidDataException("'type' is invalid, received $it")
                    }
                }
                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 (diff.asKnown().isPresent) 1 else 0) +
                    (if (path.asKnown().isPresent) 1 else 0) +
                    type.let { if (it == JsonValue.from("create_file")) 1 else 0 }

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

                return other is CreateFile &&
                    diff == other.diff &&
                    path == other.path &&
                    type == other.type &&
                    additionalProperties == other.additionalProperties
            }

            private val hashCode: Int by lazy {
                Objects.hash(diff, path, type, additionalProperties)
            }

            override fun hashCode(): Int = hashCode

            override fun toString() =
                "CreateFile{diff=$diff, path=$path, type=$type, additionalProperties=$additionalProperties}"
        }

        /** Instruction describing how to delete a file via the apply_patch tool. */
        class DeleteFile
        @JsonCreator(mode = JsonCreator.Mode.DISABLED)
        private constructor(
            private val path: JsonField<String>,
            private val type: JsonValue,
            private val additionalProperties: MutableMap<String, JsonValue>,
        ) {

            @JsonCreator
            private constructor(
                @JsonProperty("path") @ExcludeMissing path: JsonField<String> = JsonMissing.of(),
                @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            ) : this(path, type, mutableMapOf())

            /**
             * Path of the file to delete.
             *
             * @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 path(): String = path.getRequired("path")

            /**
             * Delete the specified file.
             *
             * Expected to always return the following:
             * ```java
             * JsonValue.from("delete_file")
             * ```
             *
             * 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

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

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

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

                private var path: JsonField<String>? = null
                private var type: JsonValue = JsonValue.from("delete_file")
                private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

                @JvmSynthetic
                internal fun from(deleteFile: DeleteFile) = apply {
                    path = deleteFile.path
                    type = deleteFile.type
                    additionalProperties = deleteFile.additionalProperties.toMutableMap()
                }

                /** Path of the file to delete. */
                fun path(path: String) = path(JsonField.of(path))

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

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

                /**
                 * Returns an immutable instance of [DeleteFile].
                 *
                 * Further updates to this [Builder] will not mutate the returned instance.
                 *
                 * The following fields are required:
                 * ```java
                 * .path()
                 * ```
                 *
                 * @throws IllegalStateException if any required field is unset.
                 */
                fun build(): DeleteFile =
                    DeleteFile(
                        checkRequired("path", path),
                        type,
                        additionalProperties.toMutableMap(),
                    )
            }

            private var validated: Boolean = false

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

                path()
                _type().let {
                    if (it != JsonValue.from("delete_file")) {
                        throw OpenAIInvalidDataException("'type' is invalid, received $it")
                    }
                }
                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 (path.asKnown().isPresent) 1 else 0) +
                    type.let { if (it == JsonValue.from("delete_file")) 1 else 0 }

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

                return other is DeleteFile &&
                    path == other.path &&
                    type == other.type &&
                    additionalProperties == other.additionalProperties
            }

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

            override fun hashCode(): Int = hashCode

            override fun toString() =
                "DeleteFile{path=$path, type=$type, additionalProperties=$additionalProperties}"
        }

        /** Instruction describing how to update a file via the apply_patch tool. */
        class UpdateFile
        @JsonCreator(mode = JsonCreator.Mode.DISABLED)
        private constructor(
            private val diff: JsonField<String>,
            private val path: JsonField<String>,
            private val type: JsonValue,
            private val additionalProperties: MutableMap<String, JsonValue>,
        ) {

            @JsonCreator
            private constructor(
                @JsonProperty("diff") @ExcludeMissing diff: JsonField<String> = JsonMissing.of(),
                @JsonProperty("path") @ExcludeMissing path: JsonField<String> = JsonMissing.of(),
                @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            ) : this(diff, path, type, mutableMapOf())

            /**
             * Diff to apply.
             *
             * @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 diff(): String = diff.getRequired("diff")

            /**
             * Path of the file to update.
             *
             * @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 path(): String = path.getRequired("path")

            /**
             * Update an existing file with the provided diff.
             *
             * Expected to always return the following:
             * ```java
             * JsonValue.from("update_file")
             * ```
             *
             * 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

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

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

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

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

                private var diff: JsonField<String>? = null
                private var path: JsonField<String>? = null
                private var type: JsonValue = JsonValue.from("update_file")
                private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

                @JvmSynthetic
                internal fun from(updateFile: UpdateFile) = apply {
                    diff = updateFile.diff
                    path = updateFile.path
                    type = updateFile.type
                    additionalProperties = updateFile.additionalProperties.toMutableMap()
                }

                /** Diff to apply. */
                fun diff(diff: String) = diff(JsonField.of(diff))

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

                /** Path of the file to update. */
                fun path(path: String) = path(JsonField.of(path))

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

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

                /**
                 * Returns an immutable instance of [UpdateFile].
                 *
                 * Further updates to this [Builder] will not mutate the returned instance.
                 *
                 * The following fields are required:
                 * ```java
                 * .diff()
                 * .path()
                 * ```
                 *
                 * @throws IllegalStateException if any required field is unset.
                 */
                fun build(): UpdateFile =
                    UpdateFile(
                        checkRequired("diff", diff),
                        checkRequired("path", path),
                        type,
                        additionalProperties.toMutableMap(),
                    )
            }

            private var validated: Boolean = false

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

                diff()
                path()
                _type().let {
                    if (it != JsonValue.from("update_file")) {
                        throw OpenAIInvalidDataException("'type' is invalid, received $it")
                    }
                }
                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 (diff.asKnown().isPresent) 1 else 0) +
                    (if (path.asKnown().isPresent) 1 else 0) +
                    type.let { if (it == JsonValue.from("update_file")) 1 else 0 }

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

                return other is UpdateFile &&
                    diff == other.diff &&
                    path == other.path &&
                    type == other.type &&
                    additionalProperties == other.additionalProperties
            }

            private val hashCode: Int by lazy {
                Objects.hash(diff, path, type, additionalProperties)
            }

            override fun hashCode(): Int = hashCode

            override fun toString() =
                "UpdateFile{diff=$diff, path=$path, type=$type, additionalProperties=$additionalProperties}"
        }
    }

    /** The status of the apply patch tool call. One of `in_progress` or `completed`. */
    class Status @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 IN_PROGRESS = of("in_progress")

            @JvmField val COMPLETED = of("completed")

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

        /** An enum containing [Status]'s known values. */
        enum class Known {
            IN_PROGRESS,
            COMPLETED,
        }

        /**
         * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
         *
         * An instance of [Status] 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 {
            IN_PROGRESS,
            COMPLETED,
            /** An enum member indicating that [Status] 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) {
                IN_PROGRESS -> Value.IN_PROGRESS
                COMPLETED -> Value.COMPLETED
                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) {
                IN_PROGRESS -> Known.IN_PROGRESS
                COMPLETED -> Known.COMPLETED
                else -> throw OpenAIInvalidDataException("Unknown Status: $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") }

        private var validated: Boolean = false

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

            known()
            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 (value() == Value._UNKNOWN) 0 else 1

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

            return other is Status && value == other.value
        }

        override fun hashCode() = value.hashCode()

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

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

        return other is ResponseApplyPatchToolCall &&
            id == other.id &&
            callId == other.callId &&
            operation == other.operation &&
            status == other.status &&
            type == other.type &&
            createdBy == other.createdBy &&
            additionalProperties == other.additionalProperties
    }

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

    override fun hashCode(): Int = hashCode

    override fun toString() =
        "ResponseApplyPatchToolCall{id=$id, callId=$callId, operation=$operation, status=$status, type=$type, createdBy=$createdBy, additionalProperties=$additionalProperties}"
}
