<?php

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

use Limb_Chatbot\Includes\AI_Providers\Open_Ai\Handlers\Response_Handler;
use Limb_Chatbot\Includes\Data_Objects\Dataset_Entry;
use Limb_Chatbot\Includes\Services\Collection;
use Limb_Chatbot\Includes\Services\Helper;

/**
 * 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 Response_Response_Handler extends Response_Handler {

	/**
	 * Constructs dataset entries collection based on the response's Q/A pairs
	 *
	 * @return Collection
	 * @since 1.0.0
	 */
	public function get_dataset_entries(): Collection {
		$dataset_entries = new Collection();
		$message         = ! empty( $this->get_body()->output[0]->content ) ? $this->get_body()->output[0]->content : null;
		if ( ! empty( $message[0]->text ) ) {
			$content = preg_replace( '/^```(?:json)?\s*|\s*```$/', '', trim( $message[0]->text ) );
			if ( Helper::is_probable_json( $content ) ) {
				foreach ( json_decode( $content ) as $entry ) {
					$dataset_entry        = Dataset_Entry::make();
					$dataset_entry->entry = [
						'system'   => '',
						'messages' => [
							[
								'input'  => $entry->question,
								'output' => $entry->answer,
							]
						],
						'entry_metadata' => [
							'entry_type' => 'qa',
						]
					];
					$dataset_entries->push_item( $dataset_entry );
					// Paraphrases → additional entries with same answer
					if ( ! empty( $entry->paraphrases ) && is_array( $entry->paraphrases ) ) {
						foreach ( $entry->paraphrases as $pp ) {
							if ( ! is_string( $pp ) || $pp === '' ) {
								continue;
							}
							$pp_entry        = Dataset_Entry::make();
							$pp_entry->entry = [
								'system'   => '',
								'messages' => [
									[
										'input'  => $pp,
										'output' => $entry->answer,
									]
								],
								'entry_metadata' => [
									'entry_type' => 'qa',
								]
							];
							$dataset_entries->push_item( $pp_entry );
						}
					};
				}
			}
		}

		return $dataset_entries;
	}
}