<?php
/**
 * Trait ATFPP\AI_Translate\Services\Traits\Model_Param_Tool_Config_Trait
 *
 * @since 0.7.0
 * @package ai-services
 */

namespace ATFPP\AI_Translate\Services\Traits;

use ATFPP\AI_Translate\Services\API\Types\Tool_Config;
use InvalidArgumentException;

/**
 * Trait for a model that uses `Tool_Config`.
 *
 * @since 0.7.0
 */
trait Model_Param_Tool_Config_Trait {

	/**
	 * The tool configuration.
	 *
	 * @since 0.7.0
	 * @var Tool_Config|null
	 */
	private $tool_config;

	/**
	 * Gets the tool configuration.
	 *
	 * @since 0.7.0
	 *
	 * @return Tool_Config|null The tool configuration, or null if not set.
	 */
	final protected function get_tool_config(): ?Tool_Config {
		return $this->tool_config;
	}

	/**
	 * Sets the tool configuration.
	 *
	 * @since 0.7.0
	 *
	 * @param Tool_Config $tool_config The tool configuration.
	 */
	final protected function set_tool_config( Tool_Config $tool_config ): void {
		$this->tool_config = $tool_config;
	}

	/**
	 * Sets the tool configuration if provided in the `toolConfig` model parameter.
	 *
	 * @since 0.7.0
	 *
	 * @param array<string, mixed> $model_params The model parameters.
	 *
	 * @throws InvalidArgumentException Thrown if the `toolConfig` model parameter is invalid.
	 */
	protected function set_tool_config_from_model_params( array $model_params ): void {
		if ( ! isset( $model_params['toolConfig'] ) ) {
			return;
		}

		if ( is_array( $model_params['toolConfig'] ) ) {
			$model_params['toolConfig'] = Tool_Config::from_array( $model_params['toolConfig'] );
		}

		if ( ! $model_params['toolConfig'] instanceof Tool_Config ) {
			throw new InvalidArgumentException(
				sprintf(
					'Invalid toolConfig model parameter: The value must be an array or an instance of %s.',
					Tool_Config::class
				)
			);
		}

		$this->set_tool_config( $model_params['toolConfig'] );
	}
}
