<?php

namespace Limb_Chatbot\Includes\Services\Knowledge\Knowledge_Mappers;

use Limb_Chatbot\Includes\Data_Objects\Dataset;
use Limb_Chatbot\Includes\Data_Objects\Dataset_Meta;
use Limb_Chatbot\Includes\Interfaces\Knowledge_Mapper_Interface;

class CPT_Knowledge_Mapper implements Knowledge_Mapper_Interface {

	public function get_entry_input( $object ): string {
		if ( ! $object instanceof \WP_Post ) {
			return '';
		}

		return get_the_title( $object );
	}

	public function get_entry_output( $object ): string {
		if ( ! $object instanceof \WP_Post ) {
			return '';
		}

		$title   = get_the_title( $object );
		$excerpt = wp_strip_all_tags( get_the_excerpt( $object ), true );

		// Optionally include trimmed content (adjust length or remove if not desired)
		$content = wp_strip_all_tags( apply_filters( 'the_content', $object->post_content ), true );
		$content = mb_substr( $content, 0, 1000 ); // safe limit

		// Collect taxonomy terms (categories, tags, custom taxonomies)
		$tax_output          = [];
		$taxonomies = get_object_taxonomies( $object->post_type, 'objects' );
		$dataset = Dataset::where( [
			'source'          => $object->ID,
			'source_type'     => 'cpt',
			'source_sub_type' => $object->post_type
		] );
		if ( ! $dataset->is_empty() ) {
			$dataset             = $dataset->first();
			$selected_taxonomies = $dataset instanceof Dataset ? $dataset->get_meta( 'taxonomies' ) : [];
			$selected_taxonomies = $selected_taxonomies instanceof Dataset_Meta ? $selected_taxonomies->get_meta_value() : [];
		}

		foreach ( $taxonomies as $taxonomy ) {
			if ( ! empty( $selected_taxonomies ) && ! in_array( $taxonomy->name, $selected_taxonomies ) ) {
				continue;
			}

			$terms = get_the_terms( $object, $taxonomy->name );
			if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {
				$tax_output[] = sprintf(
					'%s: %s',
					$taxonomy->label,
					implode( ', ', wp_list_pluck( $terms, 'name' ) )
				);
			}
		}

		// Build the final string (structured but simple)
		$output = implode( "\n\n", array_filter( [
			$title,
			$excerpt,
			$content,
			! empty( $tax_output ) ? implode( "\n", $tax_output ) : '',
		] ) );

		return trim( $output );
	}
}

