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

// We must include the base class file before we can extend it.
require_once plugin_dir_path( __FILE__ ) . 'class-api-base.php';

class Aitnb_Gemini_Fit_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-flash-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 ) {
		// Call the parent constructor to set the API key.
		parent::__construct( $api_key );

		// Set the model name.
		$this->model_name = $model_name;

		// Set the specific API endpoint URL for the Gemini Pro model.
		$this->api_url = 'https://generativelanguage.googleapis.com/v1/' . $this->model_name . ':generateContent';
	}

	/**
	 * A public method to simplify getting a fit recommendation.
	 *
	 * @since    1.0.0
	 * @param    array     $user_data    An array of user data (e.g., height, weight, body shape).
	 * @param    array     $size_chart   The product's size chart data.
	 * @return   string|WP_Error        The text recommendation from the AI or a WP_Error on failure.
	 */
	public function get_fit_recommendation( $user_data, $size_chart ) {
		$args = array(
			'user_data'  => $user_data,
			'size_chart' => $size_chart,
		);

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

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

		// Parse the specific Gemini response structure to get the text content.
		if ( isset( $response['candidates'][0]['content']['parts'][0]['text'] ) ) {
			return $response['candidates'][0]['content']['parts'][0]['text'];
		}

		return new WP_Error( 'invalid_gemini_response', __( 'Could not parse the fit 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['user_data'] ) || ! isset( $args['size_chart'] ) ) {
			return new WP_Error( 'missing_data', __( 'User data and size chart are required for a fit recommendation.', 'virtual-ai-fit-and-style-assistant' ) );
		}

		// --- Construct a detailed prompt for the AI ---
		$prompt  = 'You are an expert fashion AI assistant providing a size recommendation for an online shopper. ';
		$prompt .= 'Based on the following user information and the product\'s size chart, recommend the best size. ';
		$prompt .= 'Be friendly, concise, and explain your reasoning in one short sentence. Only recommend a size found in the chart. ';
		$prompt .= 'Do not add any greetings or sign-offs. Just provide the recommendation directly. ';

		$prompt .= "\n\n--- User Information ---\n";
		// Convert user data array to a string.
		foreach ( $args['user_data'] as $key => $value ) {
			$prompt .= ucwords( str_replace( '_', ' ', $key ) ) . ': ' . esc_html( $value ) . "\n";
		}

		$prompt .= "\n--- Product Size Chart ---\n";
		// Convert size chart data to a string.
		if ( isset( $args['size_chart']['chart'] ) && is_array( $args['size_chart']['chart'] ) ) {
			foreach ( $args['size_chart']['chart'] as $size => $measurements ) {
				$prompt .= 'Size ' . esc_html( $size ) . ': ' . esc_html( $measurements ) . "\n";
			}
		}

		$prompt .= "\n\nRecommendation: ";
		// --- End of prompt construction ---

		// Construct the request body as per the Gemini API documentation.
		$request_body = array(
			'contents' => array(
				array(
					'parts' => array(
						array(
							'text' => $prompt,
						),
					),
				),
			),
		);

		return $request_body;
	}
}