<?php

namespace Limb_Chatbot\Includes\Services\Knowledge\Knowledge_Mappers;

use Limb_Chatbot\Includes\Interfaces\Knowledge_Mapper_Interface;
use WP_Post;

/**
 * Knowledge mapper for WordPress posts.
 *
 * Extracts structured input (title) and output (summary, content, categories,
 * tags, and custom fields) from a WP_Post object for dataset entry generation.
 *
 * @since 1.0.0
 */
class Post_Knowledge_Mapper implements Knowledge_Mapper_Interface {

	/**
	 * Generate the dataset output content from a WordPress post.
	 *
	 * The output may include:
	 * - Summary (excerpt)
	 * - Main content
	 * - Categories
	 * - Tags
	 * - Custom fields (via filter)
	 *
	 * @param  mixed  $object  The source object, expected to be an instance of WP_Post.
	 *
	 * @return string         The formatted output content or an empty string if invalid.
	 *
	 * @since 1.0.0
	 */
	public function get_entry_output( $object ): string {
		if ( ! $object instanceof WP_Post ) {
			return '';
		}

		$parts = [];

		// Clean summary
//		if ( $summary = get_the_excerpt( $object ) ) {
//			$parts[] = trim( $summary );
//		}

		// Clean content
		if ( $content = apply_filters( 'the_content', $object->post_content ) ) {
			$parts[] = trim( $content );
		}

//		// Categories & tags (merged as "topics")
//		$topics = array_merge(
//			wp_get_post_terms( $object->ID, 'category', [ 'fields' => 'names' ] ) ?: [],
//			wp_get_post_terms( $object->ID, 'post_tag', [ 'fields' => 'names' ] ) ?: []
//		);
//		if ( $topics ) {
//			$parts[] = 'Topics: ' . implode( ', ', $topics );
//		}
//
//		// Custom fields (extendable via filter)
//		$custom_fields = apply_filters( 'lbaic_chatbot_custom_fields', [], $object );
//		foreach ( $custom_fields as $field_key ) {
//			if ( $value = get_post_meta( $object->ID, $field_key, true ) ) {
//				$parts[] = "{$field_key}: {$value}";
//			}
//		}

		// Final clean text for embeddings
		return implode( "\n\n", array_filter( $parts ) );
	}

	/**
	 * Generate the dataset input (title) from a WordPress post.
	 *
	 * @param  mixed  $object  The source object, expected to be an instance of WP_Post.
	 *
	 * @return string         The post title or an empty string if invalid.
	 *
	 * @since 1.0.0
	 */
	public function get_entry_input( $object ): string {
		if ( ! $object instanceof WP_Post ) {
			return '';
		}

		return $object->post_title;
	}
}
