<?php

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

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

/**
 * Class Response_Response_Handler
 *
 * Handles parsing responses from OpenRouter Responses API.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Router\Endpoints\Response\Handlers
 * @since 1.0.14
 */
class Response_Response_Handler extends Response_Handler {

	/**
	 * Constructs dataset entries collection based on the response's Q/A pairs.
	 *
	 * @return Collection
	 * @since 1.0.14
	 */
	public function get_dataset_entries(): Collection {
		$dataset_entries = new Collection();
		$body = $this->get_body();

		$text = null;

		if ( isset( $body->choices ) && isset( $body->choices[0]->message->content ) ) {
			$text = $body->choices[0]->message->content;
		} elseif ( isset( $body->output ) && is_array( $body->output ) && isset( $body->output[0]->content ) ) {
			$message = $body->output[0]->content;
			if ( is_array( $message ) && isset( $message[0]->text ) ) {
				$text = $message[0]->text;
			} elseif ( is_string( $message ) ) {
				$text = $message;
			}
		} elseif ( isset( $body->content ) && is_string( $body->content ) ) {
			$text = $body->content;
		}

		if ( ! empty( $text ) ) {
			$content = preg_replace( '/^```(?:json)?\s*|\s*```$/', '', trim( $text ) );
			if ( Helper::is_probable_json( $content ) ) {
				$json_data = json_decode( $content );
				if ( is_array( $json_data ) ) {
					foreach ( $json_data as $entry ) {
						if ( ! isset( $entry->question ) || ! isset( $entry->answer ) ) {
							continue;
						}
						$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 );

						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;
	}
}
