<?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;
use Limb_Chatbot\Includes\Services\Knowledge\Source_Attachment_Meta_Service;

class Manual_Knowledge_Generator implements Knowledge_Generator_Interface {

	public function generate( Dataset $dataset ): Dataset {
		$source = Helper::resolve_source_object( $dataset->get_source_type(), $dataset->get_meta_value( 'q_a' ) );
		$mapper = ( new Knowledge_Mapper_Factory() )->make( $dataset->get_source_type() );
		$answer = $mapper->get_entry_output( $source );
		if ( '' === $answer ) {
			return $dataset;
		}

		$canonical_question = trim( $mapper->get_entry_input( $source ) );
		if ( '' === $canonical_question ) {
			return $dataset;
		}

		$variations = is_array( $source['question_variations'] ?? null ) ? $source['question_variations'] : [];
		$variations = array_values(
			array_filter(
				array_unique(
					array_map(
						static function ( $variation ): string {
							return trim( (string) $variation );
						},
						$variations
					)
				),
				static function ( string $variation ) use ( $canonical_question ): bool {
					return '' !== $variation && $variation !== $canonical_question;
				}
			)
		);

		$source_content = $this->build_source_content( $canonical_question, $variations, $answer );
		$dataset->update_meta( 'source_content', $source_content );
		( new Source_Attachment_Meta_Service() )->update_dataset_attachment_meta( $dataset, $source_content );

		$entry = new Dataset_Entry();
		$entry->set_dataset_id( $dataset->get_id() );
		$entry->set_entry( [
			'system'         => '',
			'messages'       => [
				[
					'input'  => $canonical_question,
					'output' => $answer,
				],
			],
			'entry_metadata' => [
				'entry_type'            => 'qa',
				'post_title'            => $dataset->get_name(),
				'source_type'           => Dataset::SOURCE_QA,
				'canonical_question'    => $canonical_question,
				'question_variations'   => $variations,
				'is_question_variation' => false,
				'variation_index'       => null,
			],
		] );
		$entry->save();

		return $dataset;
	}

	/**
	 * Build HTML source content preview for QA datasets.
	 *
	 * @param  string  $question
	 * @param  array   $variations
	 * @param  string  $answer
	 *
	 * @return string
	 */
	private function build_source_content( string $question, array $variations, string $answer ): string {
		$html = '<h2>' . esc_html__( 'Question', 'limb-chatbot' ) . '</h2>';
		$html .= '<p>' . esc_html( $question ) . '</p>';

		if ( ! empty( $variations ) ) {
			$html .= '<h3>' . esc_html__( 'Question Variations', 'limb-chatbot' ) . '</h3><ul>';
			foreach ( $variations as $variation ) {
				$html .= '<li>' . esc_html( (string) $variation ) . '</li>';
			}
			$html .= '</ul>';
		}

		$html .= '<h2>' . esc_html__( 'Answer', 'limb-chatbot' ) . '</h2>';
		$html .= wpautop( wp_kses_post( $answer ) );

		return $html;
	}
}