<?php

declare( strict_types=1 );

namespace Limb_Chatbot\Includes\Services\System_Message\Chunks;

use Limb_Chatbot\Includes\Services\Knowledge\Knowledge_Source_Store;

/**
 * Verified Knowledge Chunk
 *
 * Provides the factual knowledge base that should be the primary source
 * for responses. Emphasizes accuracy and prevents hallucinations.
 *
 * @since 1.1.1
 */
class Verified_Knowledge_Chunk extends System_Message_Chunk {

	const MAX_CHUNKS = 10;

	/**
	 * Knowledge entries.
	 *
	 * @var array
	 */
	private array $knowledge = [];

	/**
	 * Constructor.
	 *
	 * @param  array  $knowledge  Knowledge entries to include.
	 */
	public function __construct( array $knowledge = [] ) {
		// Use provided knowledge or fetch from store
		$this->knowledge = ! empty( $knowledge ) ? $knowledge : Knowledge_Source_Store::instance()->get_sources();
	}

	public function get_title(): string {
		return 'Verified Knowledge — Primary Source';
	}

	public function get_content(): array {
		if ( $this->has_knowledge() ) {
			$lines = [
				"Use the following as the primary factual source.",
				"Do not introduce external assumptions or general training data.",
				"When answering, extract only the key facts or steps that are needed for the user’s specific question.",
				"Prefer short, high-level explanations instead of copying long sections verbatim.",
				"If the user explicitly asks for a detailed, step-by-step guide, then include more detailed steps.",
				"",
				"========================================",
				Knowledge_Source_Store::instance()->stringify_knowledge(
					$this->knowledge,
					self::MAX_CHUNKS
				),
				"========================================",
				"",
				"When the user asks for setup, configuration, or step-by-step guidance, include ALL required steps in correct logical order. Do NOT omit steps even if they seem obvious.",
			];
		} else {
			$lines = [
				"No verified knowledge is currently loaded.",
				"For setup, configuration, or procedural questions:",
				"- State lack of information only if the search returns nothing relevant."
			];
		}

		return $lines;
	}

	public function get_priority(): int {
		return 30;
	}

	/**
	 * Check if knowledge is available to include the detailed section.
	 *
	 * @return bool
	 */
	public function has_knowledge(): bool {
		return ! empty( $this->knowledge );
	}
}
