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

namespace SAAI\REST;

use SAAI\Abstracts\Abstract_AI_Agent_REST;
use SAAI\AI_Agents\Category_Description_AI as AI_Agent;
use SAAI\Classes\Category_Description;
use SAAI\Helpers\Helper;
use SAAI\Traits\Singleton_Trait;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

/**
 * Category_Description_AI class.
 *
 * @since 1.0.4
 */
class Category_Description_AI extends Abstract_AI_Agent_REST {

    use Singleton_Trait;

    /**
     * Holds the class instance object
     *
     * @since 1.0.4
     * @var Category_Description_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 description_length (text).
        if ( isset( $params['description_length'] ) ) {
            $sanitized['description_length'] = sanitize_text_field( $params['description_length'] );
        }

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

        // Sanitize array fields.
        $array_fields = array( 'tones', 'common_characteristics', 'age_focus', 'target_audience' );
        foreach ( $array_fields as $field ) {
            if ( isset( $params[ $field ] ) && is_array( $params[ $field ] ) ) {
                $sanitized[ $field ] = array_map( 'sanitize_text_field', $params[ $field ] );
            }
        }

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

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

        parent::register_routes();

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

        register_rest_route(
            $this->namespace,
            "/$this->rest_base",
            array(
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => array( $this, 'generate_category_description' ),
                'permission_callback' => array( $this, 'create_item_permissions_check' ),
            )
        );
    }

    /**
     * Generate category description.
     *
     * @since 1.0.4
     *
     * @param \WP_REST_Request $request Request object.
     * @return \WP_REST_Response Response object.
     */
    public function generate_category_description( $request ) {
        $term_id = $request['term_id'] ?? 0;
        $params  = Category_Description::sanitize_data( $request->get_params() );
        $data    = $params;

        // Resolve default language with WordPress default language.
        if ( isset( $data['language'] ) ) {
            $data['language'] = Helper::resolve_default_language( $data['language'] );
        }

        $ai = AI_Agent::instance();

        $ai->set_data( $data );
        $ai_response = $ai->send_prompt();

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

        $category_description = new Category_Description( $term_id );
        $category_description->set_data( $params ); // save the unmodified params data.
        // NOTE: data is only saved when term ID is provided.
        $category_description->save();

        $completion = $this->with_usage_data( $ai_response['completion'] );
        $response   = rest_ensure_response( $completion );

        return new WP_REST_Response( $response, 200 );
    }
}
