<?php

namespace Limb_Chatbot\Includes\Services\Knowledge\Knowledge_Mappers;


use Limb_Chatbot\Includes\Interfaces\Knowledge_Mapper_Interface;

/**
 * Knowledge mapper for manual dataset entries.
 *
 * Extracts structured input and output from an array representing
 * manually defined knowledge. Ensures normalized formatting and
 * consistent line breaks.
 *
 * @since 1.0.0
 */
class Manual_Knowledge_Mapper implements Knowledge_Mapper_Interface {

	/**
	 * Generate the dataset output content from a manual knowledge array.
	 *
	 * Normalizes line breaks and collapses multiple empty lines to ensure
	 * clean formatting.
	 *
	 * @param  mixed  $object  The source object, expected to be an array with 'output' key.
	 *
	 * @return string         The formatted output content, or an empty string if invalid.
	 *
	 * @since 1.0.0
	 */
	public function get_entry_output( $object ): string {
		if ( empty( $object ) || ! is_array( $object ) ) {
			return '';
		}

		$output = $object['answer'] ?? $object['output'] ?? '';
		if ( ! is_string( $output ) ) {
			return '';
		}

		// Normalize line breaks
		$output = str_replace( [ "\r\n", "\r" ], "\n", $output );

		// Collapse multiple empty lines into a single empty line
		$output = preg_replace( "/\n{2,}/", "\n\n", $output );


		return trim( (string) $output );
	}

	/**
	 * Generate the dataset entry input from a manual knowledge array.
	 *
	 * Returns the 'input' key trimmed for clean usage in dataset entries.
	 *
	 * @param  mixed  $object  The source object, expected to be an array with 'input' key.
	 *
	 * @return string         The dataset input, or an empty string if invalid.
	 *
	 * @since 1.0.0
	 */
	public function get_entry_input( $object ): string {
		if ( empty( $object ) || ! is_array( $object ) ) {
			return '';
		}

		$input = $object['question'] ?? $object['input'] ?? '';

		return trim( (string) $input );
	}
}
