<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Ai\Utilities;

use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Utilities\Fine_Tuning_Utility as Global_Utility;
use Limb_Chatbot\Includes\Data_Objects\Config;
use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints\Fine_Tuning_Endpoint;
use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Open_Ai;

/**
 * Utility class for managing fine-tuning operations using the OpenAI provider.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Ai\Utilities
 * @since 1.0.0
 */
class Fine_Tuning_Utility {

	/**
	 * Configuration object associated with this utility.
	 *
	 * May be null if no configuration is found or set.
	 *
	 * @since 1.0.0
	 * @var Config|null
	 */
	public ?Config $config;

	/**
	 * Global fine-tuning utility instance for shared operations.
	 *
	 * @since 1.0.0
	 * @var Global_Utility
	 */
	public Global_Utility $global_utility;

	/**
	 * Endpoint instance handling fine-tuning API calls.
	 *
	 * @since 1.0.0
	 * @var Fine_Tuning_Endpoint
	 */
	public Fine_Tuning_Endpoint $endpoint;

	/**
	 * Constructor.
	 *
	 * Initializes the utility with a global utility instance, sets the default config if missing,
	 * and initializes the fine-tuning endpoint.
	 *
	 * @since 1.0.0
	 *
	 * @param Global_Utility $global_utility Global fine-tuning utility instance.
	 */
	public function __construct( Global_Utility $global_utility ) {
		$this->global_utility = $global_utility;
		if ( is_null( $this->global_utility->config ) ) {
			$this->config = Config::where( [ 'default' => true, 'related_to' => Open_Ai::class ] )->first();
		}
		$this->endpoint = new Fine_Tuning_Endpoint( $this );
	}

	/**
	 * Creates a fine-tuning job via the endpoint.
	 *
	 * Delegates the creation process to the Fine_Tuning_Endpoint instance.
	 *
	 * @return array Result of the fine-tuning creation operation.
	 * @throws Exception
	 * @since 1.0.0
	 *
	 */
	public function create() {
		return $this->endpoint->create();
	}

	/**
	 * Retrieves fine-tuning job details via the endpoint.
	 *
	 * Delegates the retrieval process to the Fine_Tuning_Endpoint instance.
	 *
	 * @return array Result of the fine-tuning retrieval operation.
	 * @throws Exception
	 * @since 1.0.0
	 *
	 */
	public function retrieve() {
		return $this->endpoint->retrieve();
	}

	/**
	 * Returns the configuration object used by this utility.
	 *
	 * @since 1.0.0
	 *
	 * @return Config|null Configuration object or null if not set.
	 */
	public function get_config(): ?Config {
		return $this->config;
	}
}