<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints\Fine_Tuning\Handlers;

use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Open_Ai;
use Limb_Chatbot\Includes\Data_Objects\AI_Model_Meta;
use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Handlers\Response_Handler;

/**
 * Class Fine_Tuning_Response_Handler
 *
 * Handles and parses responses related to fine-tuning jobs for OpenAI models.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Ai\Endpoints\Fine_Tuning\Handlers
 * @since 1.0.0
 */
class Fine_Tuning_Response_Handler extends Response_Handler {

	/**
	 * Array of meta objects representing fine-tuning job data.
	 *
	 * @var AI_Model_Meta[] $metas
	 * @since 1.0.0
	 */
	protected array $metas;

	/**
	 * Whether to cast response body to array when parsing.
	 *
	 * @var bool|null $body_cast_array
	 * @since 1.0.0
	 */
	protected ?bool $body_cast_array = true;

	/**
	 * Maps external fine-tuning statuses to internal AI_Model_Meta constants.
	 *
	 * @var array<string,int>
	 * @since 1.0.0
	 */
	protected static array $status_mapper
		= [
			'validating_files' => AI_Model_Meta::FINE_TUNING_STARTED,
			'running'          => AI_Model_Meta::FINE_TUNING_STARTED,
			'queued'           => AI_Model_Meta::FINE_TUNING_STARTED,
			'paused'           => AI_Model_Meta::FINE_TUNING_PAUSED,
			'cancelled'        => AI_Model_Meta::FINE_TUNING_CANCELED,
			'succeeded'        => AI_Model_Meta::FINE_TUNING_COMPLETED,
			'failed'           => AI_Model_Meta::FINE_TUNING_FAILED,
		];

	/**
	 * Parses the response body and populates the model metas.
	 *
	 * @return void
	 * @since 1.0.0
	 */
	public function parse(): void {
		parent::parse();
		$this->set_metas( $this->define_metas() );
	}

	/**
	 * Defines and builds an array of AI_Model_Meta objects from response data.
	 *
	 * @return AI_Model_Meta[]
	 * @since 1.0.0
	 */
	protected function define_metas(): array {
		foreach ( $this->get_body() as $key => $value ) {
			$this->metas[] = AI_Model_Meta::make( [ 'meta_key' => Open_Ai::$id . "_$key", 'meta_value' => $value ] );
		}
		$this->metas[] = AI_Model_Meta::make( [ 'meta_key' => 'status', 'meta_value' => self::$status_mapper[ $this->get_body()['status'] ] ] );

		return $this->metas;
	}

	/**
	 * Returns the array of AI_Model_Meta objects.
	 *
	 * @return AI_Model_Meta[]
	 * @since 1.0.0
	 */
	public function get_metas(): array {
		return $this->metas;
	}

	/**
	 * Sets the metas array.
	 *
	 * @param AI_Model_Meta[] $model_meta Array of meta objects.
	 * @return void
	 * @since 1.0.0
	 */
	public function set_metas( array $model_meta ): void {
		$this->metas = $model_meta;
	}
}
