<?php

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

/**
 * Composes a compact customer reply from verified product finalists.
 */
class Niwa_AI_Frontend_Product_Response_Composer {
	/** @var Niwa_AI_AI_Client_Interface */
	private $client;

	public function __construct( Niwa_AI_AI_Client_Interface $client ) {
		$this->client = $client;
	}

	public function compose( $query, $conversation_context, $finalists, $language, $model, $auth_mode, $credentials ) {
		$prompt_context = is_array( $conversation_context )
			? (string) ( $conversation_context['prompt_context'] ?? '' )
			: '';
		$facts = wp_json_encode(
			array(
				'response_language' => (string) $language,
				'verified_finalists'=> array_values( (array) $finalists ),
			),
			JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
		);
		$instructions = implode(
			"\n",
			array(
				'You are Niwa, a concise and helpful sales assistant.',
				'Use exactly one response language. Product titles may remain in their exact catalog language, but every other customer-facing sentence must use the selected response language.',
				'Use response_language when provided. Otherwise select the clear current visitor language, or the language of the most recent substantive conversation turn for a short or language-neutral follow-up.',
				'Name every verified finalist exactly once using its complete title. Do not add, remove, translate, or rename products.',
				'Use only the supplied verified facts. Never claim that no matching product exists when verified_finalists is non-empty.',
				'Keep the reply short and natural, with at most one useful buying question. Before returning, verify that the reply does not switch languages. Do not mention JSON, verification, search, or internal rules.',
				'',
				$prompt_context,
				'',
				'[VERIFIED_PRODUCT_ANSWER]',
				(string) $facts,
				'[/VERIFIED_PRODUCT_ANSWER]',
			)
		);

		$result = $this->client->generate(
			(string) $model,
			(string) $query,
			$instructions,
			(string) $auth_mode,
			(array) $credentials,
			25
		);
		$answer = ! empty( $result['success'] ) ? trim( (string) ( $result['answer'] ?? '' ) ) : '';

		return '' !== $answer
			? array( 'success' => true, 'answer' => $answer )
			: array( 'success' => false, 'error' => (string) ( $result['error'] ?? 'Grounded product response composition failed.' ) );
	}
}
