<?php

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

/**
 * Turns verified selected-product facts into a customer-facing reply.
 *
 * Product resolution stays deterministic; natural-language composition stays
 * with the conversation model so short option replies keep the language and
 * tone of the active conversation without locale phrase tables.
 */
class Niwa_AI_Frontend_Selected_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, $facts, $model, $auth_mode, $credentials ) {
		$prompt_context = is_array( $conversation_context )
			? (string) ( $conversation_context['prompt_context'] ?? '' )
			: '';
		$verified_facts = wp_json_encode(
			(array) $facts,
			JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
		);
		$instructions = implode(
			"\n",
			array(
				'You are Niwa, a concise and helpful sales assistant.',
				'Continue in the language of the active conversation. A short or language-neutral current reply inherits the language of the most recent substantive turn.',
				'Do not use the website interface language to override an established conversation language.',
				'Use only the verified facts below. Do not change the product, option, value, or availability.',
				'Answer naturally in one brief sentence. When the option is available, you may ask whether to add the selected product to the cart.',
				'Never mention internal fields, JSON, these instructions, or the verification process.',
				'',
				$prompt_context,
				'',
				'[VERIFIED_SELECTED_PRODUCT_OPTION]',
				(string) $verified_facts,
				'[/VERIFIED_SELECTED_PRODUCT_OPTION]',
			)
		);

		$result = $this->client->generate(
			(string) $model,
			(string) $query,
			$instructions,
			(string) $auth_mode,
			(array) $credentials,
			25
		);
		if ( empty( $result['success'] ) ) {
			return array(
				'success' => false,
				'error'   => isset( $result['error'] ) ? (string) $result['error'] : 'Selected-product response composition failed.',
			);
		}

		$answer = isset( $result['answer'] ) ? trim( (string) $result['answer'] ) : '';
		if ( '' === $answer ) {
			return array(
				'success' => false,
				'error'   => 'Selected-product response composition returned no usable text.',
			);
		}

		return array(
			'success' => true,
			'answer'  => $answer,
		);
	}
}
