<?php
/**
 * Author: Rymera
 *
 * @package SAAI\REST
 */

namespace SAAI\REST;

use SAAI\Traits\Singleton_Trait;
use SAAI\Abstracts\Abstract_AI_Agent_REST;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;
use SAAI\AI_Agents\Product_Summaries_AI as AI_Agent;

/**
 * Product_Summaries_AI class.
 *
 * @since 1.0.0
 */
class Product_Summaries_AI extends Abstract_AI_Agent_REST {

    use Singleton_Trait;

    const PRODUCT_SUMMARY_META_KEY = 'saai_product_summary';

    /**
     * Holds the class instance object
     *
     * @since 1.0.2
     * @var Product_Summaries_AI $instance object
     */
    protected static $instance;

    /**
     * Sanitize settings data before saving.
     *
     * @param array $params The parameters to sanitize.
     * @return array The sanitized parameters.
     */
    protected function sanitize_settings_data( $params ) {
        $sanitized = array();

        // Sanitize enabled setting.
        if ( isset( $params['enabled'] ) ) {
            $sanitized['enabled'] = sanitize_text_field( $params['enabled'] );
        }

        // Sanitize includeFeaturesNum (integer).
        if ( isset( $params['includeFeaturesNum'] ) ) {
            $sanitized['includeFeaturesNum'] = absint( $params['includeFeaturesNum'] );
        }

        // Sanitize missing short description check settings.
        if ( isset( $params['missing_desc_check'] ) ) {
            $sanitized['missing_desc_check'] = sanitize_text_field( $params['missing_desc_check'] );
        }

        if ( isset( $params['missing_desc_frequency'] ) ) {
            $sanitized['missing_desc_frequency'] = sanitize_text_field( $params['missing_desc_frequency'] );
        }

        if ( isset( $params['missing_desc_limit'] ) ) {
            $sanitized['missing_desc_limit'] = absint( $params['missing_desc_limit'] );
        }

        // Sanitize language (text).
        if ( isset( $params['language'] ) ) {
            $sanitized['language'] = sanitize_text_field( $params['language'] );
        }

        // Apply filter for additional sanitization.
        return apply_filters( 'saai_sanitize_product_summaries_settings', $sanitized, $params );
    }

    /**
     * Register the routes.
     *
     * @since 1.0.2
     * @return void
     */
    public function register_routes() {

        parent::register_routes();

        register_rest_route(
            $this->namespace,
            "/$this->rest_base/(?P<product_id>[\d]+)/generate",
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'generate_product_summary' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
            )
        );
    }

    /**
     * Generate product summary.
     *
     * @param WP_REST_Request $request Request object.
     *
     * @return WP_REST_Response|WP_Error
     */
    public function generate_product_summary( $request ) {

        $product_id = absint( $request->get_param( 'product_id' ) );
        $product    = wc_get_product( $product_id );
        $response   = AI_Agent::instance()->run_agent_query( array( 'product_id' => $product_id ) );

        if ( is_wp_error( $response ) ) {
            return $response;
        } elseif ( empty( $response['completion']['summary'] ) ) {
            return new WP_Error( 'no_summary', __( 'No summary found.', 'storeagent-ai-for-woocommerce' ), array( 'status' => 400 ) );
        }

        /***************************************************************************
         * Allow developers to handle the summary
         ***************************************************************************
         *
         * We'll return the summary if it's already handled by third party plugins.
         */
        $summary = apply_filters( 'saai_product_summaries_ai_summary', null, $response );
        if ( ! empty( $summary ) ) {

            // Save the summary to the product meta.
            AI_Agent::instance()->save_object_data( $product, array( 'summary' => $summary ) );

            $response_data = apply_filters( 'saai_product_summaries_ai_response', compact( 'product_id', 'summary' ) );

            return $this->rest_response( $this->with_usage_data( $response_data ), $request );
        }

        /***************************************************************************
         * Process the summary from the AI response
         ***************************************************************************
         *
         * We'll parse the summary and features from the AI response and apply the
         * disclaimer if it's enabled.
         */
        [
            'summary'  => $summary,
            'features' => $features,
        ] = wp_parse_args(
            $response['completion'],
            array(
                'summary'  => '',
                'features' => '',
            )
        );

        $summary       = AI_Agent::append_features_to_summary( $summary, $features );
        $response_data = apply_filters( 'saai_product_summaries_ai_response', compact( 'product_id', 'summary' ) );

        return $this->rest_response( $this->with_usage_data( $response_data ), $request );
    }
}
