<?php

namespace Limb_Chatbot\Includes\Services\Knowledge\Knowledge_Mappers;

use Limb_Chatbot\Includes\Interfaces\Knowledge_Mapper_Interface;
use WP_Term;

/**
 * Knowledge mapper for WordPress terms.
 *
 * Extracts structured input and output from a WP_Term object for dataset
 * entry generation. Output may include description, taxonomy, parent term,
 * and custom term meta fields.
 *
 * @since 1.0.0
 */
class Term_Knowledge_Mapper implements Knowledge_Mapper_Interface {

	/**
	 * Generate the dataset output content from a WordPress term.
	 *
	 * The output may include:
	 * - Summary (term description)
	 * - Taxonomy
	 * - Parent term
	 * - Custom term meta (via filter)
	 *
	 * @param  mixed  $object  The source object, expected to be an instance of WP_Term.
	 *
	 * @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_Term ) {
			return '';
		}

		$parts = [];

		// Summary (term description)
		if ( ! empty( $object->description ) ) {
			$parts[] = "Summary:" . trim( $object->description );
		}

		// Taxonomy
		if ( ! empty( $object->taxonomy ) ) {
			$parts[] = "Taxonomy:" . $object->taxonomy;
		}

		// Parent term
		if ( ! empty( $object->parent ) ) {
			$parent = get_term( $object->parent );
			if ( $parent && ! is_wp_error( $parent ) ) {
				$parts[] = "Parent Term:" . $parent->name;
			}
		}

		// Custom term meta (via filter so it's configurable)
		$custom_fields = apply_filters( 'lbaic_chatbot_custom_term_fields', [], $object );
		if ( ! empty( $custom_fields ) ) {
			$meta_lines = [];
			foreach ( $custom_fields as $field_key ) {
				$value = get_term_meta( $object->term_id, $field_key, true );
				if ( $value ) {
					$meta_lines[] = "{$field_key}: {$value}";
				}
			}
			if ( $meta_lines ) {
				$parts[] = "Custom Fields:" . implode( "\n", $meta_lines );
			}
		}

		return implode( "\n\n", $parts );
	}

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

		return $object->name;
	}
}
