<?php
/**
 * RAG service HTTP client.
 *
 * Communicates with external RAG microservice for intelligent
 * text chunk selection using wp_remote_post().
 *
 * @package MasterQuiz
 * @since   1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class MasterQuiz_Rag_Client
 *
 * @since 1.0.0
 */
class MasterQuiz_Rag_Client {

	/**
	 * RAG service base URL.
	 *
	 * @var string
	 */
	private $service_url;

	/**
	 * Whether the service is enabled.
	 *
	 * @var bool
	 */
	private $enabled;

	/**
	 * Request timeout in seconds.
	 *
	 * @var int
	 */
	private $timeout;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		$this->enabled     = (bool) get_option( 'masterquiz_rag_enabled', 0 );
		$this->service_url = rtrim( esc_url_raw( get_option( 'masterquiz_rag_url', '' ) ), '/' );
		$this->timeout     = absint( get_option( 'masterquiz_rag_timeout', 30 ) );

		if ( empty( $this->service_url ) ) {
			$this->enabled = false;
		}
	}

	/**
	 * Check if the RAG service is enabled and configured.
	 *
	 * @since 1.0.0
	 *
	 * @return bool
	 */
	public function is_enabled() {
		return $this->enabled;
	}

	/**
	 * Select the most relevant chunks from text using the RAG service.
	 *
	 * @since 1.0.0
	 *
	 * @param string      $text       The full text to chunk.
	 * @param int         $max_chunks Maximum number of chunks to select.
	 * @param int         $max_chars  Maximum characters per chunk.
	 * @param string|null $query      Optional query for semantic search.
	 * @return array|null Array with 'chunks', 'context', 'method' keys, or null on failure.
	 */
	public function select_chunks( $text, $max_chunks = 6, $max_chars = 14000, $query = null ) {
		if ( ! $this->enabled ) {
			return null;
		}

		// Limit text size to prevent timeouts.
		$max_text_size = 500000;
		if ( strlen( $text ) > $max_text_size ) {
			$text        = substr( $text, 0, $max_text_size );
			$last_period = strrpos( $text, '.' );
			if ( false !== $last_period ) {
				$text = substr( $text, 0, $last_period + 1 );
			}
		}

		$payload = array(
			'text'                => $text,
			'max_chunks'          => $max_chunks,
			'max_chars_per_chunk' => $max_chars,
		);

		if ( null !== $query ) {
			$payload['query'] = $query;
		}

		$response = wp_remote_post(
			$this->service_url . '/select-chunks',
			array(
				'timeout' => $this->timeout,
				'headers' => array( 'Content-Type' => 'application/json' ),
				'body'    => wp_json_encode( $payload ),
			)
		);

		if ( is_wp_error( $response ) ) {
			MasterQuiz_Logger::warning( 'RAG service request failed.', array( 'error' => $response->get_error_message() ) );
			return null;
		}

		$code = wp_remote_retrieve_response_code( $response );
		if ( 200 !== $code ) {
			MasterQuiz_Logger::warning( 'RAG service returned non-200.', array( 'code' => $code ) );
			return null;
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );
		if ( ! is_array( $body ) || empty( $body['success'] ) ) {
			MasterQuiz_Logger::warning( 'RAG service returned error.', array( 'body' => $body ) );
			return null;
		}

		return array(
			'chunks'  => isset( $body['chunks'] ) ? $body['chunks'] : array(),
			'context' => isset( $body['context'] ) ? $body['context'] : '',
			'method'  => isset( $body['method'] ) ? $body['method'] : 'unknown',
		);
	}

	/**
	 * Check RAG service health.
	 *
	 * @since 1.0.0
	 *
	 * @return bool True if service is available and healthy.
	 */
	public function health_check() {
		if ( ! $this->enabled ) {
			return false;
		}

		$response = wp_remote_get(
			$this->service_url . '/health',
			array( 'timeout' => 5 )
		);

		if ( is_wp_error( $response ) ) {
			return false;
		}

		return 200 === wp_remote_retrieve_response_code( $response );
	}
}
