<?php

namespace CommerceBird;

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

if ( ! class_exists( 'CMBIRD_AI_Product_Blocks_Generator' ) ) {
	/**
	 * Generates AI-powered product block content for WooCommerce products.
	 */
	class CMBIRD_AI_Product_Blocks_Generator {

		const META_KEY         = '_cmbird_ai_review_summary';
		const META_UPDATED_KEY = '_cmbird_ai_review_summary_updated';
		const META_QA_LOG_KEY  = '_cmbird_ai_dynamic_qa_log';
		const REVIEW_COUNT     = 10;
		const OPTION_ENABLED   = 'cmbird_ai_review_summary_enabled';
		const OPTION_PROMPT    = 'cmbird_ai_review_summary_prompt';

		/**
		 * Holds the last generation error message.
		 *
		 * @var string
		 */
		private string $last_error_message = '';

		/**
		 * Return the last generation error message.
		 *
		 * @return string
		 */
		public function get_last_error_message(): string {
			return $this->last_error_message;
		}

		/**
		 * Generate and store summary for one product.
		 *
		 * @param int $product_id Product ID.
		 * @return bool
		 */
		public function generate( int $product_id ): bool {
			$this->last_error_message = '';

			if ( $product_id <= 0 || ! function_exists( 'wp_ai_client_prompt' ) ) {
				$this->last_error_message = __( 'AI generation is not available in this environment.', 'commercebird' );
				return false;
			}

			$reviews = get_comments(
				array(
					'post_id' => $product_id,
					'status'  => 'approve',
					'number'  => self::REVIEW_COUNT,
					'orderby' => 'comment_date',
					'order'   => 'DESC',
					'type'    => 'review',
				)
			);

			if ( empty( $reviews ) ) {
				$this->last_error_message = __( 'No approved product reviews were found to summarize.', 'commercebird' );
				return false;
			}

			$product = \wc_get_product( $product_id );
			if ( ! $product ) {
				$this->last_error_message = __( 'Unable to load the selected product.', 'commercebird' );
				return false;
			}

			$prompt_builder = \wp_ai_client_prompt( $this->build_prompt( $reviews, $product->get_name() ) )
				->using_max_tokens( 300 );

			if ( ! $prompt_builder->is_supported_for_text_generation() ) {
				$this->last_error_message = __( 'No supported AI provider is configured for text generation.', 'commercebird' );
				return false;
			}

			$summary = $prompt_builder->generate_text();
			if ( is_wp_error( $summary ) || ! is_string( $summary ) || '' === trim( $summary ) ) {
				if ( is_wp_error( $summary ) ) {
					$this->last_error_message = $summary->get_error_message();
				} else {
					$this->last_error_message = __( 'AI provider returned an empty summary.', 'commercebird' );
				}
				return false;
			}

			update_post_meta( $product_id, self::META_KEY, sanitize_textarea_field( $summary ) );
			update_post_meta( $product_id, self::META_UPDATED_KEY, time() );

			return true;
		}

		/**
		 * Answer a visitor question about a product using available product context.
		 *
		 * @param int    $product_id Product ID.
		 * @param string $question Visitor question.
		 * @return string|
		 */
		public function answer_question( int $product_id, string $question ): string {
			$this->last_error_message = '';

			$question = trim( sanitize_text_field( $question ) );
			if ( $product_id <= 0 || '' === $question ) {
				$this->last_error_message = __( 'Please provide a valid question.', 'commercebird' );
				return '';
			}

			if ( ! function_exists( 'wp_ai_client_prompt' ) ) {
				$this->last_error_message = __( 'AI generation is not available in this environment.', 'commercebird' );
				return '';
			}

			$product = \wc_get_product( $product_id );
			if ( ! $product ) {
				$this->last_error_message = __( 'Unable to load the selected product.', 'commercebird' );
				return '';
			}

			$reviews          = $this->get_recent_reviews( $product_id );
			$existing_q_and_a = $this->get_existing_q_and_a( $product_id );
			$prompt           = $this->build_question_prompt( $product, $question, $reviews, $existing_q_and_a );

			$prompt_builder = \wp_ai_client_prompt( $prompt )->using_max_tokens( 380 );
			if ( ! $prompt_builder->is_supported_for_text_generation() ) {
				$this->last_error_message = __( 'No supported AI provider is configured for text generation.', 'commercebird' );
				return '';
			}

			$answer = $prompt_builder->generate_text();
			if ( is_wp_error( $answer ) || ! is_string( $answer ) || '' === trim( $answer ) ) {
				if ( is_wp_error( $answer ) ) {
					$this->last_error_message = $answer->get_error_message();
				} else {
					$this->last_error_message = __( 'AI provider returned an empty answer.', 'commercebird' );
				}
				return '';
			}

			$answer = sanitize_textarea_field( $answer );
			$this->persist_question_answer( $product_id, $question, $answer );

			return $answer;
		}

		/**
		 * Get recent approved product reviews.
		 *
		 * @param int $product_id Product ID.
		 * @return array
		 */
		private function get_recent_reviews( int $product_id ): array {
			return get_comments(
				array(
					'post_id' => $product_id,
					'status'  => 'approve',
					'number'  => self::REVIEW_COUNT,
					'orderby' => 'comment_date',
					'order'   => 'DESC',
					'type'    => 'review',
				)
			);
		}

		/**
		 * Build question-answering prompt.
		 *
		 * @param \WC_Product $product Product object.
		 * @param string      $question Visitor question.
		 * @param array       $reviews Recent reviews.
		 * @param array       $q_and_a Existing Q&A items.
		 * @return string
		 */
		private function build_question_prompt( \WC_Product $product, string $question, array $reviews, array $q_and_a ): string {
			$review_text = '';
			if ( ! empty( $reviews ) ) {
				foreach ( $reviews as $index => $review ) {
					$rating       = get_comment_meta( $review->comment_ID, 'rating', true );
					$review_text .= sprintf(
						"Review %d (Rating: %s/5): %s\n",
						$index + 1,
						$rating ? sanitize_text_field( (string) $rating ) : 'N/A',
						sanitize_textarea_field( $review->comment_content )
					);
				}
			} else {
				$review_text = 'No recent review context available.';
			}

			$q_and_a_text = '';
			if ( ! empty( $q_and_a ) ) {
				foreach ( $q_and_a as $item ) {
					if ( empty( $item['question'] ) || empty( $item['answer'] ) ) {
						continue;
					}
					$q_and_a_text .= sprintf(
						"Q: %s\nA: %s\n",
						sanitize_textarea_field( (string) $item['question'] ),
						sanitize_textarea_field( (string) $item['answer'] )
					);
				}
			}
			if ( '' === $q_and_a_text ) {
				$q_and_a_text = 'No previous Q&A available yet.';
			}

			$product_description = wp_strip_all_tags( (string) $product->get_description() );
			if ( '' === trim( $product_description ) ) {
				$product_description = wp_strip_all_tags( (string) $product->get_short_description() );
			}

			return sprintf(
				"You are an assistant answering product questions for an ecommerce product page.\n\nProduct Name: %s\n\nProduct Description:\n%s\n\nRecent Reviews:\n%s\n\nExisting Q&A:\n%s\n\nVisitor Question:\n%s\n\nRules:\n1. Answer in 2-5 concise sentences.\n2. Use only evidence from description, reviews, and existing Q&A.\n3. If information is uncertain or missing, say that clearly.\n4. Do not invent technical claims, certifications, or compatibility details.\n5. Keep tone helpful and purchase-focused.",
				sanitize_text_field( $product->get_name() ),
				sanitize_textarea_field( $product_description ),
				$review_text,
				$q_and_a_text,
				sanitize_textarea_field( $question )
			);
		}

		/**
		 * Return existing Q&A history for a product.
		 *
		 * @param int $product_id Product ID.
		 * @return array
		 */
		public function get_existing_q_and_a( int $product_id ): array {
			$history = get_post_meta( $product_id, self::META_QA_LOG_KEY, true );
			if ( ! is_array( $history ) ) {
				return array();
			}

			// Keep newest first and cap context size for prompt stability.
			$history = array_reverse( $history );
			return array_slice( $history, 0, 8 );
		}

		/**
		 * Persist question and answer pair for future Q&A context.
		 *
		 * @param int    $product_id Product ID.
		 * @param string $question Visitor question.
		 * @param string $answer AI answer.
		 * @return void
		 */
		private function persist_question_answer( int $product_id, string $question, string $answer ): void {
			$history = get_post_meta( $product_id, self::META_QA_LOG_KEY, true );
			if ( ! is_array( $history ) ) {
				$history = array();
			}

			$history[] = array(
				'question'   => sanitize_textarea_field( $question ),
				'answer'     => sanitize_textarea_field( $answer ),
				'created_at' => time(),
			);

			if ( count( $history ) > 30 ) {
				$history = array_slice( $history, -30 );
			}

			update_post_meta( $product_id, self::META_QA_LOG_KEY, $history );
		}

		/**
		 * Build the AI prompt payload.
		 *
		 * @param array  $reviews Reviews.
		 * @param string $product_name Product title.
		 * @return string
		 */
		private function build_prompt( array $reviews, string $product_name ): string {
			$review_text = '';
			foreach ( $reviews as $index => $review ) {
				$rating       = get_comment_meta( $review->comment_ID, 'rating', true );
				$review_text .= sprintf(
					"Review %d (Rating: %s/5):\n%s\n\n",
					$index + 1,
					$rating ? sanitize_text_field( (string) $rating ) : 'N/A',
					sanitize_textarea_field( $review->comment_content )
				);
			}

			$prompt_template = get_option( self::OPTION_PROMPT, $this->default_prompt() );

			return str_replace(
				array( '{count}', '{product_name}', '{reviews}' ),
				array( (string) count( $reviews ), sanitize_text_field( $product_name ), $review_text ),
				(string) $prompt_template
			);
		}

		/**
		 * Default prompt template.
		 *
		 * @return string
		 */
		private function default_prompt(): string {
			return 'Summarize the following {count} customer reviews for "{product_name}" in 2-3 sentences. Focus on recurring themes, sentiment, and key pros/cons. Be factual and neutral. Do not invent details not present in the reviews.' . "\n\n" . 'Reviews:' . "\n" . '{reviews}';
		}
	}
}

if ( ! class_exists( 'CMBIRD_AI_Review_Summary_Generator' ) && class_exists( 'CMBIRD_AI_Product_Blocks_Generator' ) ) {
	class_alias( __NAMESPACE__ . '\\CMBIRD_AI_Product_Blocks_Generator', __NAMESPACE__ . '\\CMBIRD_AI_Review_Summary_Generator' );
}
