<?php

namespace Limb_Chatbot\Includes\Services\Knowledge\Source_Object_Fetchers;

use Limb_Chatbot\Includes\Data_Objects\Dataset;
use Limb_Chatbot\Includes\Interfaces\Source_Fetcher_Interface;

/**
 * Class Manual_Source_Fetcher
 *
 * Fetches dataset entries for manually defined knowledge sources.
 *
 * Implements the Source_Fetcher_Interface contract to provide
 * a consistent dataset entry structure.
 *
 * @package Limb_Chatbot\Includes\Services\Knowledge\Source_Object_Fetchers
 * @since 1.0.0
 */
class Manual_Source_Fetcher implements Source_Fetcher_Interface {
	public function fetch( array $item, array $config ): array {
		$paged    = max( 1, (int) ( $item['paged'] ?? 1 ) );
		$per_page = max( 1, (int) ( $item['per_page'] ?? 1 ) );
		$offset   = ( $paged - 1 ) * $per_page;
		$qa_items = $this->normalize_qa_items( $config['q_a'] ?? null );
		$slice    = array_slice( $qa_items, $offset, $per_page );

		$objects = [];
		foreach ( $slice as $relative_index => $qa_item ) {
			if ( ! is_array( $qa_item ) ) {
				continue;
			}

			$question   = trim( (string) ( $qa_item['question'] ?? '' ) );
			$answer     = trim( (string) ( $qa_item['answer'] ?? '' ) );
			$variations = array_values(
				array_filter(
					array_unique(
						array_map(
							static function ( $variation ): string {
								return trim( (string) $variation );
							},
							is_array( $qa_item['question_variations'] ?? null ) ? $qa_item['question_variations'] : []
						)
					),
					static function ( string $variation ): bool {
						return '' !== $variation;
					}
				)
			);

			$normalized_qa = [
				'question'            => $question,
				'question_variations' => $variations,
				'answer'              => $answer,
			];

			$absolute_index = $offset + $relative_index;
			$source_key     = 'qa:' . md5( wp_json_encode( [ $question, $variations, $answer ] ) . ':' . $absolute_index );

			$objects[] = [
				'source'          => $source_key,
				'source_type'     => Dataset::SOURCE_QA,
				'source_sub_type' => null,
				'q_a'             => $normalized_qa,
			];
		}

		return $objects;
	}

	/**
	 * Normalize legacy/new Q&A payloads to a list of items.
	 *
	 * @param  mixed  $qa_payload
	 *
	 * @return array
	 */
	private function normalize_qa_items( $qa_payload ): array {
		if ( ! is_array( $qa_payload ) ) {
			return [];
		}
		if ( isset( $qa_payload['question'] ) || isset( $qa_payload['input'] ) ) {
			$question = trim( (string) ( $qa_payload['question'] ?? $qa_payload['input'] ?? '' ) );
			$answer   = trim( (string) ( $qa_payload['answer'] ?? $qa_payload['output'] ?? '' ) );
			$variations = is_array( $qa_payload['question_variations'] ?? null ) ? $qa_payload['question_variations'] : [];

			return [
				[
					'question'            => $question,
					'question_variations' => $variations,
					'answer'              => $answer,
				],
			];
		}

		return $qa_payload;
	}
}
