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

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

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


		return trim( $object['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 '';
		}

		return trim( $object['input'] );
	}
}
