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

/** A tool call that executes one or more shell commands in a managed environment. */
class ResponseFunctionShellToolCall
@JsonCreator(mode = JsonCreator.Mode.DISABLED)
private constructor(
    private val id: JsonField<String>,
    private val action: JsonField<Action>,
    private val callId: JsonField<String>,
    private val environment: JsonField<Environment>,
    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("action") @ExcludeMissing action: JsonField<Action> = JsonMissing.of(),
        @JsonProperty("call_id") @ExcludeMissing callId: JsonField<String> = JsonMissing.of(),
        @JsonProperty("environment")
        @ExcludeMissing
        environment: JsonField<Environment> = 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, action, callId, environment, status, type, createdBy, mutableMapOf())

    /**
     * The unique ID of the shell 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 shell commands and limits that describe how to run the 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 action(): Action = action.getRequired("action")

    /**
     * The unique ID of the shell 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")

    /**
     * Represents the use of a local environment to perform shell actions.
     *
     * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
     *   server responded with an unexpected value).
     */
    fun environment(): Optional<Environment> = environment.getOptional("environment")

    /**
     * The status of the shell call. One of `in_progress`, `completed`, or `incomplete`.
     *
     * @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 `shell_call`.
     *
     * Expected to always return the following:
     * ```java
     * JsonValue.from("shell_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 [action].
     *
     * Unlike [action], this method doesn't throw if the JSON field has an unexpected type.
     */
    @JsonProperty("action") @ExcludeMissing fun _action(): JsonField<Action> = action

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

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

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

        private var id: JsonField<String>? = null
        private var action: JsonField<Action>? = null
        private var callId: JsonField<String>? = null
        private var environment: JsonField<Environment>? = null
        private var status: JsonField<Status>? = null
        private var type: JsonValue = JsonValue.from("shell_call")
        private var createdBy: JsonField<String> = JsonMissing.of()
        private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

        @JvmSynthetic
        internal fun from(responseFunctionShellToolCall: ResponseFunctionShellToolCall) = apply {
            id = responseFunctionShellToolCall.id
            action = responseFunctionShellToolCall.action
            callId = responseFunctionShellToolCall.callId
            environment = responseFunctionShellToolCall.environment
            status = responseFunctionShellToolCall.status
            type = responseFunctionShellToolCall.type
            createdBy = responseFunctionShellToolCall.createdBy
            additionalProperties = responseFunctionShellToolCall.additionalProperties.toMutableMap()
        }

        /** The unique ID of the shell 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 shell commands and limits that describe how to run the tool call. */
        fun action(action: Action) = action(JsonField.of(action))

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

        /** The unique ID of the shell 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 }

        /** Represents the use of a local environment to perform shell actions. */
        fun environment(environment: Environment?) = environment(JsonField.ofNullable(environment))

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

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

        /** Alias for calling [environment] with `Environment.ofLocal(local)`. */
        fun environment(local: ResponseLocalEnvironment) = environment(Environment.ofLocal(local))

        /**
         * Alias for calling [environment] with
         * `Environment.ofContainerReference(containerReference)`.
         */
        fun environment(containerReference: ResponseContainerReference) =
            environment(Environment.ofContainerReference(containerReference))

        /**
         * Alias for calling [environment] with the following:
         * ```java
         * ResponseContainerReference.builder()
         *     .containerId(containerId)
         *     .build()
         * ```
         */
        fun containerReferenceEnvironment(containerId: String) =
            environment(ResponseContainerReference.builder().containerId(containerId).build())

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

    private var validated: Boolean = false

    /**
     * Validates that the types of all values in this object match their expected types recursively.
     *
     * This method is _not_ forwards compatible with new types from the API for existing fields.
     *
     * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
     *   expected type.
     */
    fun validate(): ResponseFunctionShellToolCall = apply {
        if (validated) {
            return@apply
        }

        id()
        action().validate()
        callId()
        environment().ifPresent { it.validate() }
        status().validate()
        _type().let {
            if (it != JsonValue.from("shell_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) +
            (action.asKnown().getOrNull()?.validity() ?: 0) +
            (if (callId.asKnown().isPresent) 1 else 0) +
            (environment.asKnown().getOrNull()?.validity() ?: 0) +
            (status.asKnown().getOrNull()?.validity() ?: 0) +
            type.let { if (it == JsonValue.from("shell_call")) 1 else 0 } +
            (if (createdBy.asKnown().isPresent) 1 else 0)

    /** The shell commands and limits that describe how to run the tool call. */
    class Action
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val commands: JsonField<List<String>>,
        private val maxOutputLength: JsonField<Long>,
        private val timeoutMs: JsonField<Long>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("commands")
            @ExcludeMissing
            commands: JsonField<List<String>> = JsonMissing.of(),
            @JsonProperty("max_output_length")
            @ExcludeMissing
            maxOutputLength: JsonField<Long> = JsonMissing.of(),
            @JsonProperty("timeout_ms")
            @ExcludeMissing
            timeoutMs: JsonField<Long> = JsonMissing.of(),
        ) : this(commands, maxOutputLength, timeoutMs, mutableMapOf())

        /**
         * @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 commands(): List<String> = commands.getRequired("commands")

        /**
         * Optional maximum number of characters to return from each command.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun maxOutputLength(): Optional<Long> = maxOutputLength.getOptional("max_output_length")

        /**
         * Optional timeout in milliseconds for the commands.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun timeoutMs(): Optional<Long> = timeoutMs.getOptional("timeout_ms")

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

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

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

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

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

            private var commands: JsonField<MutableList<String>>? = null
            private var maxOutputLength: JsonField<Long>? = null
            private var timeoutMs: JsonField<Long>? = null
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(action: Action) = apply {
                commands = action.commands.map { it.toMutableList() }
                maxOutputLength = action.maxOutputLength
                timeoutMs = action.timeoutMs
                additionalProperties = action.additionalProperties.toMutableMap()
            }

            fun commands(commands: List<String>) = commands(JsonField.of(commands))

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

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

            /** Optional maximum number of characters to return from each command. */
            fun maxOutputLength(maxOutputLength: Long?) =
                maxOutputLength(JsonField.ofNullable(maxOutputLength))

            /**
             * Alias for [Builder.maxOutputLength].
             *
             * This unboxed primitive overload exists for backwards compatibility.
             */
            fun maxOutputLength(maxOutputLength: Long) = maxOutputLength(maxOutputLength as Long?)

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

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

            /** Optional timeout in milliseconds for the commands. */
            fun timeoutMs(timeoutMs: Long?) = timeoutMs(JsonField.ofNullable(timeoutMs))

            /**
             * Alias for [Builder.timeoutMs].
             *
             * This unboxed primitive overload exists for backwards compatibility.
             */
            fun timeoutMs(timeoutMs: Long) = timeoutMs(timeoutMs as Long?)

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

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

            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 [Action].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .commands()
             * .maxOutputLength()
             * .timeoutMs()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): Action =
                Action(
                    checkRequired("commands", commands).map { it.toImmutable() },
                    checkRequired("maxOutputLength", maxOutputLength),
                    checkRequired("timeoutMs", timeoutMs),
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): Action = apply {
            if (validated) {
                return@apply
            }

            commands()
            maxOutputLength()
            timeoutMs()
            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 =
            (commands.asKnown().getOrNull()?.size ?: 0) +
                (if (maxOutputLength.asKnown().isPresent) 1 else 0) +
                (if (timeoutMs.asKnown().isPresent) 1 else 0)

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

            return other is Action &&
                commands == other.commands &&
                maxOutputLength == other.maxOutputLength &&
                timeoutMs == other.timeoutMs &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(commands, maxOutputLength, timeoutMs, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "Action{commands=$commands, maxOutputLength=$maxOutputLength, timeoutMs=$timeoutMs, additionalProperties=$additionalProperties}"
    }

    /** Represents the use of a local environment to perform shell actions. */
    @JsonDeserialize(using = Environment.Deserializer::class)
    @JsonSerialize(using = Environment.Serializer::class)
    class Environment
    private constructor(
        private val local: ResponseLocalEnvironment? = null,
        private val containerReference: ResponseContainerReference? = null,
        private val _json: JsonValue? = null,
    ) {

        /** Represents the use of a local environment to perform shell actions. */
        fun local(): Optional<ResponseLocalEnvironment> = Optional.ofNullable(local)

        /** Represents a container created with /v1/containers. */
        fun containerReference(): Optional<ResponseContainerReference> =
            Optional.ofNullable(containerReference)

        fun isLocal(): Boolean = local != null

        fun isContainerReference(): Boolean = containerReference != null

        /** Represents the use of a local environment to perform shell actions. */
        fun asLocal(): ResponseLocalEnvironment = local.getOrThrow("local")

        /** Represents a container created with /v1/containers. */
        fun asContainerReference(): ResponseContainerReference =
            containerReference.getOrThrow("containerReference")

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

        /**
         * Maps this instance's current variant to a value of type [T] using the given [visitor].
         *
         * Note that this method is _not_ forwards compatible with new variants from the API, unless
         * [visitor] overrides [Visitor.unknown]. To handle variants not known to this version of
         * the SDK gracefully, consider overriding [Visitor.unknown]:
         * ```java
         * import com.openai.core.JsonValue;
         * import java.util.Optional;
         *
         * Optional<String> result = environment.accept(new Environment.Visitor<Optional<String>>() {
         *     @Override
         *     public Optional<String> visitLocal(ResponseLocalEnvironment local) {
         *         return Optional.of(local.toString());
         *     }
         *
         *     // ...
         *
         *     @Override
         *     public Optional<String> unknown(JsonValue json) {
         *         // Or inspect the `json`.
         *         return Optional.empty();
         *     }
         * });
         * ```
         *
         * @throws OpenAIInvalidDataException if [Visitor.unknown] is not overridden in [visitor]
         *   and the current variant is unknown.
         */
        fun <T> accept(visitor: Visitor<T>): T =
            when {
                local != null -> visitor.visitLocal(local)
                containerReference != null -> visitor.visitContainerReference(containerReference)
                else -> visitor.unknown(_json)
            }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): Environment = apply {
            if (validated) {
                return@apply
            }

            accept(
                object : Visitor<Unit> {
                    override fun visitLocal(local: ResponseLocalEnvironment) {
                        local.validate()
                    }

                    override fun visitContainerReference(
                        containerReference: ResponseContainerReference
                    ) {
                        containerReference.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 visitLocal(local: ResponseLocalEnvironment) = local.validity()

                    override fun visitContainerReference(
                        containerReference: ResponseContainerReference
                    ) = containerReference.validity()

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

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

            return other is Environment &&
                local == other.local &&
                containerReference == other.containerReference
        }

        override fun hashCode(): Int = Objects.hash(local, containerReference)

        override fun toString(): String =
            when {
                local != null -> "Environment{local=$local}"
                containerReference != null -> "Environment{containerReference=$containerReference}"
                _json != null -> "Environment{_unknown=$_json}"
                else -> throw IllegalStateException("Invalid Environment")
            }

        companion object {

            /** Represents the use of a local environment to perform shell actions. */
            @JvmStatic fun ofLocal(local: ResponseLocalEnvironment) = Environment(local = local)

            /** Represents a container created with /v1/containers. */
            @JvmStatic
            fun ofContainerReference(containerReference: ResponseContainerReference) =
                Environment(containerReference = containerReference)
        }

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

            /** Represents the use of a local environment to perform shell actions. */
            fun visitLocal(local: ResponseLocalEnvironment): T

            /** Represents a container created with /v1/containers. */
            fun visitContainerReference(containerReference: ResponseContainerReference): T

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

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

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

                when (type) {
                    "local" -> {
                        return tryDeserialize(node, jacksonTypeRef<ResponseLocalEnvironment>())
                            ?.let { Environment(local = it, _json = json) }
                            ?: Environment(_json = json)
                    }
                    "container_reference" -> {
                        return tryDeserialize(node, jacksonTypeRef<ResponseContainerReference>())
                            ?.let { Environment(containerReference = it, _json = json) }
                            ?: Environment(_json = json)
                    }
                }

                return Environment(_json = json)
            }
        }

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

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

    /** The status of the shell call. One of `in_progress`, `completed`, or `incomplete`. */
    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")

            @JvmField val INCOMPLETE = of("incomplete")

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

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

        /**
         * 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,
            INCOMPLETE,
            /** 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
                INCOMPLETE -> Value.INCOMPLETE
                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
                INCOMPLETE -> Known.INCOMPLETE
                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

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        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 ResponseFunctionShellToolCall &&
            id == other.id &&
            action == other.action &&
            callId == other.callId &&
            environment == other.environment &&
            status == other.status &&
            type == other.type &&
            createdBy == other.createdBy &&
            additionalProperties == other.additionalProperties
    }

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

    override fun hashCode(): Int = hashCode

    override fun toString() =
        "ResponseFunctionShellToolCall{id=$id, action=$action, callId=$callId, environment=$environment, status=$status, type=$type, createdBy=$createdBy, additionalProperties=$additionalProperties}"
}
