<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/**
 * Handles communication with the Google Gemini API for style recommendations.
 *
 * @link       https://trynbuy.edubrazeal.com/
 * @since      1.0.0
 *
 * @package    Ai_Try_N_Buy
 * @subpackage Ai_Try_N_Buy/services
 */

require_once plugin_dir_path( __FILE__ ) . 'class-api-base.php';

class Aitnb_Gemini_Style_Service extends Aitnb_Api_Base {

	/**
	 * The specific Gemini model to be used for the request.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $model_name    The model name (e.g., 'gemini-2.5-pro-latest').
	 */
	protected $model_name;

	/**
	 * Constructor. Sets the API key, model name, and the specific API URL for the Gemini service.
	 *
	 * @since    1.0.0
	 * @param    string    $api_key       The API key for the service.
	 * @param    string    $model_name    The specific model to use for the request.
	 */
	public function __construct( $api_key, $model_name ) {
		parent::__construct( $api_key );
		$this->model_name = $model_name;
		$this->api_url    = 'https://generativelanguage.googleapis.com/v1/' . $this->model_name . ':generateContent';
	}

	/**
	 * A public method to simplify getting style recommendations.
	 *
	 * @since    1.0.0
	 * @param    array     $current_product    Details of the product being viewed.
	 * @param    array     $product_catalog    A list of other products to recommend from.
	 * @return   array|WP_Error               An array of recommended product IDs/SKUs or a WP_Error.
	 */
	public function get_style_recommendations( $current_product, $product_catalog ) {
		$args = array(
			'current_product' => $current_product,
			'product_catalog' => $product_catalog,
		);

		$response = $this->make_request( $args );

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

		if ( isset( $response['candidates'][0]['content']['parts'][0]['text'] ) ) {
			$raw_text = $response['candidates'][0]['content']['parts'][0]['text'];
			// The prompt asks for a comma-separated list, so we explode it into an array.
			$recommended_skus = array_map( 'trim', explode( ',', $raw_text ) );
			return array_filter( $recommended_skus ); // Return a clean array of SKUs.
		}

		return new WP_Error( 'invalid_gemini_response', __( 'Could not parse the style recommendation from the API response.', 'virtual-ai-fit-and-style-assistant' ) );
	}

	/**
	 * Builds the body of the request for the Gemini API.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @param    array      $args    The arguments for the request.
	 * @return   array|WP_Error      The formatted request body or a WP_Error.
	 */
	protected function build_request_body( $args ) {
		if ( ! isset( $args['current_product'] ) || ! isset( $args['product_catalog'] ) ) {
			return new WP_Error( 'missing_data', __( 'Current product and product catalog are required for a style recommendation.', 'virtual-ai-fit-and-style-assistant' ) );
		}

		// --- Construct a detailed prompt for the AI Stylist ---
		$prompt  = "You are an expert AI fashion stylist for an e-commerce website.\n";
		$prompt .= "A customer is viewing the following item:\n";
		$prompt .= " - Name: " . esc_html( $args['current_product']['name'] ) . ", SKU: " . esc_html( $args['current_product']['sku'] ) . "\n\n";

		$prompt .= "From the list of available products below, recommend up to 3 items that would create a great outfit with the item above.\n";
		$prompt .= "--- Available Products ---\n";

		foreach ( $args['product_catalog'] as $product ) {
			$prompt .= " - Name: " . esc_html( $product['name'] ) . ", SKU: " . esc_html( $product['sku'] ) . "\n";
		}

		$prompt .= "\nIMPORTANT: Respond ONLY with a comma-separated list of the recommended product SKUs. Do not add any other text, explanations, or greetings. Example response: SKU001,SKU003,SKU008";
		// --- End of prompt construction ---

		$request_body = array(
			'contents'         => array(
				array(
					'parts' => array(
						array(
							'text' => $prompt,
						),
					),
				),
			),
			'generationConfig' => array(
				'temperature'     => 0.7,
				'maxOutputTokens' => 5024,
			),
		);

		return $request_body;
	}
}