<?php

namespace Limb_Chatbot\Includes\Services\Knowledge\Generators;

use Limb_Chatbot\Includes\Data_Objects\Dataset;
use Limb_Chatbot\Includes\Data_Objects\Dataset_Entry;
use Limb_Chatbot\Includes\Factories\Knowledge_Mapper_Factory;
use Limb_Chatbot\Includes\Interfaces\Knowledge_Generator_Interface;
use Limb_Chatbot\Includes\Services\Helper;

class CPT_Knowledge_Generator implements Knowledge_Generator_Interface {

	public function generate( Dataset $dataset ): Dataset {
		$mapper = ( new Knowledge_Mapper_Factory() )->make( $dataset->get_source_type() );
		$object = Helper::resolve_source_object( $dataset->get_source_type(), $dataset->get_source() );

		// Store dataset in a filter context so mapper can access it reliably
		// This ensures jet_engine_custom_fields and other custom fields work correctly
		add_filter( 'lbaic_cpt_mapper_dataset_context', function() use ( $dataset ) {
			return $dataset;
		}, 10 );

		$output = $mapper->get_entry_output( $object );
		$input  = $mapper->get_entry_input( $object );

		// Clean up filter
		remove_all_filters( 'lbaic_cpt_mapper_dataset_context' );

		$entry = new Dataset_Entry();
		$entry->set_dataset_id( $dataset->get_id() );
		$entry->set_entry( array(
			'system'   => '',
			'messages' => [
				[
					'input'  => $input,
					'output' => $output,
				]
			]
		) );

		$entry->save();

		return $dataset;
	}
}

