<?php
/**
 * REST API endpoints.
 *
 * @package CatalogPilot\AiStudio
 */

namespace CatalogPilot\AiStudio;

use CatalogPilot\AiStudio\Providers;

defined( 'ABSPATH' ) || exit;

final class REST_API {

	const NAMESPACE_V1 = 'cpais/v1';

	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
	}

	public function register_routes() {
		register_rest_route(
			self::NAMESPACE_V1,
			'/settings',
			array(
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_settings' ),
					'permission_callback' => array( $this, 'permission_manage' ),
				),
				array(
					'methods'             => \WP_REST_Server::EDITABLE,
					'callback'            => array( $this, 'update_settings' ),
					'permission_callback' => array( $this, 'permission_manage' ),
				),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/test-key',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'test_key' ),
				'permission_callback' => array( $this, 'permission_manage' ),
				'args'                => array(
					'provider' => array( 'type' => 'string', 'required' => true ),
					'kind'     => array( 'type' => 'string' ),
					'api_key'  => array( 'type' => 'string' ),
					'model'    => array( 'type' => 'string' ),
				),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/generate',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'generate' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/generate-seo',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'generate_seo' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/apply-seo',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'apply_seo' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/generate-image',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'generate_image' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/attach-image',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'attach_image' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/products',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'list_products' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/bulk/start',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'bulk_start' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/bulk/status',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'bulk_status' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/bulk/cancel',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'bulk_cancel' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/bulk/clear',
			array(
				'methods'             => \WP_REST_Server::DELETABLE,
				'callback'            => array( $this, 'bulk_clear' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/bulk/retry-failed',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'bulk_retry_failed' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/translate',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'translate' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/generate-alt',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'generate_alt' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/generate-taxonomy',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'generate_taxonomy' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/apply-taxonomy',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'apply_taxonomy' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/cache/flush',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'cache_flush' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/scan-missing',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'scan_missing' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/generate-faq',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'generate_faq' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/apply-faq',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'apply_faq' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/get-faq',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_faq' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
				'args'                => array(
					'product_id' => array( 'type' => 'integer', 'required' => true ),
				),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/generate-review-summary',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'generate_review_summary' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/apply-review-summary',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'apply_review_summary' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/get-review-summary',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_review_summary' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
				'args'                => array(
					'product_id' => array( 'type' => 'integer', 'required' => true ),
				),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/remove-background',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'remove_background' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/generate-image-variants',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'generate_image_variants' ),
				'permission_callback' => array( $this, 'permission_edit_products' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1, '/generate-tags',
			array( 'methods' => \WP_REST_Server::CREATABLE, 'callback' => array( $this, 'generate_tags' ), 'permission_callback' => array( $this, 'permission_edit_products' ) )
		);
		register_rest_route(
			self::NAMESPACE_V1, '/apply-tags',
			array( 'methods' => \WP_REST_Server::CREATABLE, 'callback' => array( $this, 'apply_tags' ), 'permission_callback' => array( $this, 'permission_edit_products' ) )
		);
		register_rest_route(
			self::NAMESPACE_V1, '/generate-attributes',
			array( 'methods' => \WP_REST_Server::CREATABLE, 'callback' => array( $this, 'generate_attributes' ), 'permission_callback' => array( $this, 'permission_edit_products' ) )
		);
		register_rest_route(
			self::NAMESPACE_V1, '/apply-attributes',
			array( 'methods' => \WP_REST_Server::CREATABLE, 'callback' => array( $this, 'apply_attributes' ), 'permission_callback' => array( $this, 'permission_edit_products' ) )
		);
		register_rest_route(
			self::NAMESPACE_V1, '/generate-variation-description',
			array( 'methods' => \WP_REST_Server::CREATABLE, 'callback' => array( $this, 'generate_variation_description' ), 'permission_callback' => array( $this, 'permission_edit_products' ) )
		);
		register_rest_route(
			self::NAMESPACE_V1, '/apply-variation-description',
			array( 'methods' => \WP_REST_Server::CREATABLE, 'callback' => array( $this, 'apply_variation_description' ), 'permission_callback' => array( $this, 'permission_edit_products' ) )
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/export',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'export_settings' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);

		register_rest_route(
			self::NAMESPACE_V1,
			'/import',
			array(
				'methods'             => \WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'import_settings' ),
				'permission_callback' => array( $this, 'permission_manage' ),
			)
		);
	}

	public function permission_manage() {
		return current_user_can( 'manage_woocommerce' );
	}

	public function permission_edit_products( $request = null ) {
		if ( ! current_user_can( 'edit_products' ) ) {
			return false;
		}
		if ( $request instanceof \WP_REST_Request ) {
			$product_id = (int) $request->get_param( 'product_id' );
			if ( $product_id > 0 ) {
				if ( 'product' !== get_post_type( $product_id ) ) {
					return new \WP_Error( 'cpais_invalid_product', __( 'Invalid product.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 404 ) );
				}
				if ( ! current_user_can( 'edit_post', $product_id ) ) {
					return new \WP_Error( 'cpais_forbidden_product', __( 'You cannot edit this product.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 403 ) );
				}
			}
		}
		return true;
	}

	/**
	 * Reject generation requests if the user hasn't accepted the third-party
	 * data transmission disclosure.
	 */
	private function require_consent() {
		$settings = Settings::get_all();
		if ( empty( $settings['privacy_consent'] ) ) {
			return new \WP_Error(
				'cpais_consent_required',
				__( 'Please accept the third-party data transmission disclosure on the Settings → Privacy tab before generating content.', 'catalogpilot-ai-studio-for-woocommerce' ),
				array( 'status' => 403 )
			);
		}
		return true;
	}

	public function get_settings() {
		$settings = Settings::get_all();

		$response = array(
			'active_provider'       => $settings['active_provider'],
			'active_image_provider' => $settings['active_image_provider'],
			'default_tone'          => $settings['default_tone'],
			'default_length'        => $settings['default_length'],
			'default_language'      => $settings['default_language'],
			'cache_enabled'         => ! empty( $settings['cache_enabled'] ),
			'cache_ttl'             => (int) $settings['cache_ttl'],
			'cache_size'            => Cache::size(),
			'privacy_consent'       => ! empty( $settings['privacy_consent'] ),
			'delete_data_on_uninstall' => ! empty( $settings['delete_data_on_uninstall'] ),
			'faq_schema_enabled'    => ! empty( $settings['faq_schema_enabled'] ),
			'faq_default_count'     => (int) $settings['faq_default_count'],
			'review_summary_display' => ! empty( $settings['review_summary_display'] ),
			'review_min_count'      => (int) $settings['review_min_count'],
			'bg_remover_model'      => (string) ( $settings['bg_remover_model'] ?? '' ),
			'seo_integration'       => SEO::integration_label(),
			'options'               => self::option_definitions(),
		);

		foreach ( Settings::text_provider_ids() as $id ) {
			$response[ $id . '_model' ]    = $settings[ $id . '_model' ]    ?? '';
			$response[ $id . '_key_mask' ] = Settings::mask_key( $settings[ $id . '_api_key' ] ?? '' );
			$response[ 'has_' . $id . '_key' ] = '' !== ( $settings[ $id . '_api_key' ] ?? '' );
		}

		foreach ( array( 'openai', 'replicate', 'gemini', 'stability' ) as $id ) {
			$response[ 'image_' . $id . '_model' ]    = $settings[ 'image_' . $id . '_model' ]    ?? '';
			$response[ 'image_' . $id . '_key_mask' ] = Settings::mask_key( $settings[ 'image_' . $id . '_api_key' ] ?? '' );
			$response[ 'has_image_' . $id . '_key' ]  = '' !== ( $settings[ 'image_' . $id . '_api_key' ] ?? '' );
		}

		return rest_ensure_response( $response );
	}

	public function update_settings( \WP_REST_Request $request ) {
		$payload = $request->get_json_params();
		if ( ! is_array( $payload ) ) {
			$payload = $request->get_params();
		}
		Settings::update( $payload );
		return $this->get_settings();
	}

	public function test_key( \WP_REST_Request $request ) {
		$provider_id = sanitize_key( $request->get_param( 'provider' ) );
		$kind        = sanitize_key( $request->get_param( 'kind' ) ?: 'text' );
		$api_key     = $request->get_param( 'api_key' );
		$model       = sanitize_text_field( $request->get_param( 'model' ) );

		$settings = Settings::get_all();

		if ( null === $api_key || '' === trim( (string) $api_key ) ) {
			$key_field = 'image' === $kind ? 'image_' . $provider_id . '_api_key' : $provider_id . '_api_key';
			$api_key   = $settings[ $key_field ] ?? '';
			if ( '' === $model ) {
				$model_field = 'image' === $kind ? 'image_' . $provider_id . '_model' : $provider_id . '_model';
				$model       = $settings[ $model_field ] ?? '';
			}
		} else {
			$api_key = trim( (string) $api_key );
		}

		if ( 'image' === $kind ) {
			$provider = Providers\cpais_image_factory( $provider_id, $api_key, $model );
		} else {
			$provider = Providers\cpais_factory( $provider_id, $api_key, $model );
		}

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

		$result = $provider->test_connection();
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( array( 'success' => true ) );
	}

	public function generate( \WP_REST_Request $request ) {
		$consent = $this->require_consent();
		if ( is_wp_error( $consent ) ) {
			return $consent;
		}
		$product = $this->get_product_from_request( $request );
		if ( is_wp_error( $product ) ) {
			return $product;
		}

		$params   = $request->get_json_params() ?: $request->get_params();
		$settings = array_merge( Settings::get_all(), $params );

		$result = Generator::run_text( $product, $settings );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	public function generate_seo( \WP_REST_Request $request ) {
		$consent = $this->require_consent();
		if ( is_wp_error( $consent ) ) {
			return $consent;
		}
		$product = $this->get_product_from_request( $request );
		if ( is_wp_error( $product ) ) {
			return $product;
		}

		$params   = $request->get_json_params() ?: $request->get_params();
		$settings = array_merge( Settings::get_all(), $params );

		$result = Generator::run_seo( $product, $settings );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	public function apply_seo( \WP_REST_Request $request ) {
		$product_id = absint( $request->get_param( 'product_id' ) );
		$data       = $request->get_param( 'data' );
		if ( ! is_array( $data ) ) {
			$data = array();
		}
		$result = SEO::apply( $product_id, $data );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return rest_ensure_response( array( 'applied' => $result, 'integration' => SEO::integration_label() ) );
	}

	public function generate_image( \WP_REST_Request $request ) {
		$consent = $this->require_consent();
		if ( is_wp_error( $consent ) ) {
			return $consent;
		}
		$product = $this->get_product_from_request( $request );
		if ( is_wp_error( $product ) ) {
			return $product;
		}

		$params   = $request->get_json_params() ?: $request->get_params();
		$settings = array_merge( Settings::get_all(), $params );

		if ( empty( $settings['image_provider'] ) ) {
			$settings['image_provider'] = $settings['active_image_provider'] ?? 'openai';
		}

		$result = Generator::run_image( $product, $settings );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		return rest_ensure_response( $result );
	}

	public function attach_image( \WP_REST_Request $request ) {
		$product_id    = absint( $request->get_param( 'product_id' ) );
		$attachment_id = absint( $request->get_param( 'attachment_id' ) );
		$as            = sanitize_key( $request->get_param( 'as' ) ?: 'featured' );
		$ok            = Media::attach_to_product( $attachment_id, $product_id, $as );
		return rest_ensure_response( array( 'success' => (bool) $ok ) );
	}

	public function list_products( \WP_REST_Request $request ) {
		$search  = sanitize_text_field( $request->get_param( 'search' ) ?? '' );
		$page    = max( 1, absint( $request->get_param( 'page' ) ?? 1 ) );
		$perpage = max( 1, min( 100, absint( $request->get_param( 'per_page' ) ?? 20 ) ) );
		$status  = sanitize_key( $request->get_param( 'status' ) ?? 'publish' );

		$cache_key = Cache::key_for(
			'products',
			array( 'q' => $search, 'page' => $page, 'per_page' => $perpage, 'status' => $status )
		);
		$cached = Cache::get( $cache_key );
		if ( null !== $cached ) {
			return rest_ensure_response( $cached );
		}

		$args = array(
			'post_type'      => 'product',
			'post_status'    => 'any' === $status ? array( 'publish', 'draft', 'private' ) : $status,
			'posts_per_page' => $perpage,
			'paged'          => $page,
			'orderby'        => 'date',
			'order'          => 'DESC',
			's'              => $search,
		);
		$query = new \WP_Query( $args );
		$items = array();
		foreach ( $query->posts as $p ) {
			$items[] = array(
				'id'        => $p->ID,
				'title'     => $p->post_title,
				'status'    => $p->post_status,
				'thumbnail' => get_the_post_thumbnail_url( $p->ID, 'thumbnail' ),
			);
		}

		$payload = array(
			'items'    => $items,
			'total'    => (int) $query->found_posts,
			'pages'    => (int) $query->max_num_pages,
			'page'     => $page,
			'per_page' => $perpage,
		);

		Cache::set( $cache_key, $payload );
		return rest_ensure_response( $payload );
	}

	public function bulk_start( \WP_REST_Request $request ) {
		$consent = $this->require_consent();
		if ( is_wp_error( $consent ) ) {
			return $consent;
		}
		$params      = $request->get_json_params() ?: $request->get_params();
		$product_ids = is_array( $params['product_ids'] ?? null ) ? $params['product_ids'] : array();
		unset( $params['product_ids'] );
		$result = Bulk::start( $product_ids, $params );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return rest_ensure_response( $result );
	}

	public function bulk_status() {
		return rest_ensure_response( Bulk::status() ?: array( 'status' => 'idle' ) );
	}

	public function bulk_cancel() {
		return rest_ensure_response( array( 'success' => Bulk::cancel() ) );
	}

	public function bulk_clear() {
		return rest_ensure_response( array( 'success' => Bulk::clear() ) );
	}

	public function bulk_retry_failed() {
		$result = Bulk::retry_failed();
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return rest_ensure_response( $result );
	}

	public function translate( \WP_REST_Request $request ) {
		$consent = $this->require_consent();
		if ( is_wp_error( $consent ) ) {
			return $consent;
		}
		$product = $this->get_product_from_request( $request );
		if ( is_wp_error( $product ) ) {
			return $product;
		}
		$params   = $request->get_json_params() ?: $request->get_params();
		$settings = array_merge( Settings::get_all(), $params );
		$result   = Generator::run_translate( $product, $settings );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return rest_ensure_response( $result );
	}

	public function generate_alt( \WP_REST_Request $request ) {
		$consent = $this->require_consent();
		if ( is_wp_error( $consent ) ) {
			return $consent;
		}
		$params        = $request->get_json_params() ?: $request->get_params();
		$attachment_id = absint( $params['attachment_id'] ?? 0 );
		$apply         = ! empty( $params['apply'] );

		$context = array();
		if ( ! empty( $params['product_id'] ) ) {
			$product = wc_get_product( absint( $params['product_id'] ) );
			if ( $product ) {
				$context['product_title'] = $product->get_name();
				$cats = wp_get_post_terms( $product->get_id(), 'product_cat', array( 'fields' => 'names' ) );
				if ( ! is_wp_error( $cats ) ) {
					$context['categories'] = $cats;
				}
			}
		}

		$settings = array_merge( Settings::get_all(), $params );
		$result   = Generator::run_alt_text( $attachment_id, $context, $settings );
		if ( is_wp_error( $result ) ) {
			return $result;
		}

		if ( $apply && ! empty( $result['alt_text'] ) ) {
			Generator::apply_alt_text( $attachment_id, $result['alt_text'] );
			$result['applied'] = true;
		}

		return rest_ensure_response( $result );
	}

	public function generate_taxonomy( \WP_REST_Request $request ) {
		$consent = $this->require_consent();
		if ( is_wp_error( $consent ) ) {
			return $consent;
		}
		$params   = $request->get_json_params() ?: $request->get_params();
		$term_id  = absint( $params['term_id'] ?? 0 );
		$taxonomy = sanitize_key( $params['taxonomy'] ?? 'product_cat' );

		$settings = array_merge( Settings::get_all(), $params );
		$result   = Generator::run_taxonomy( $term_id, $taxonomy, $settings );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return rest_ensure_response( $result );
	}

	public function cache_flush() {
		Cache::flush();
		return rest_ensure_response( array( 'success' => true, 'size' => Cache::size() ) );
	}

	public function scan_missing( \WP_REST_Request $request ) {
		$limit  = absint( $request->get_param( 'limit' ) );
		$result = Scanner::scan( $limit > 0 ? $limit : 500 );
		return rest_ensure_response( $result );
	}

	public function generate_faq( \WP_REST_Request $request ) {
		$consent = $this->require_consent();
		if ( is_wp_error( $consent ) ) {
			return $consent;
		}
		$product = $this->get_product_from_request( $request );
		if ( is_wp_error( $product ) ) {
			return $product;
		}
		$params   = $request->get_json_params() ?: $request->get_params();
		$settings = array_merge( Settings::get_all(), $params );
		$result   = Generator::run_faq( $product, $settings );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return rest_ensure_response( $result );
	}

	public function apply_faq( \WP_REST_Request $request ) {
		$params     = $request->get_json_params() ?: $request->get_params();
		$product_id = absint( $params['product_id'] ?? 0 );
		$faq        = $params['faq'] ?? array();
		if ( ! is_array( $faq ) ) {
			$faq = array();
		}
		if ( ! $product_id || 'product' !== get_post_type( $product_id ) ) {
			return new \WP_Error( 'cpais_invalid_product', __( 'Product not found.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 404 ) );
		}
		$saved = FAQ::save( $product_id, $faq );
		if ( false === $saved ) {
			return new \WP_Error( 'cpais_faq_save_failed', __( 'Could not save FAQ.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 500 ) );
		}
		return rest_ensure_response( array( 'success' => true, 'count' => $saved ) );
	}

	public function get_faq( \WP_REST_Request $request ) {
		$product_id = absint( $request->get_param( 'product_id' ) );
		if ( ! $product_id ) {
			return new \WP_Error( 'cpais_invalid_product', __( 'Product not found.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 404 ) );
		}
		return rest_ensure_response( array( 'faq' => FAQ::get( $product_id ) ) );
	}

	public function generate_review_summary( \WP_REST_Request $request ) {
		$consent = $this->require_consent();
		if ( is_wp_error( $consent ) ) {
			return $consent;
		}
		$product = $this->get_product_from_request( $request );
		if ( is_wp_error( $product ) ) {
			return $product;
		}
		$params   = $request->get_json_params() ?: $request->get_params();
		$settings = array_merge( Settings::get_all(), $params );
		$result   = Generator::run_review_summary( $product, $settings );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return rest_ensure_response( $result );
	}

	public function apply_review_summary( \WP_REST_Request $request ) {
		$params     = $request->get_json_params() ?: $request->get_params();
		$product_id = absint( $params['product_id'] ?? 0 );
		$summary    = (string) ( $params['summary'] ?? '' );
		$meta       = is_array( $params['meta'] ?? null ) ? $params['meta'] : array();
		if ( ! $product_id || 'product' !== get_post_type( $product_id ) ) {
			return new \WP_Error( 'cpais_invalid_product', __( 'Product not found.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 404 ) );
		}
		$saved = Review::save( $product_id, $summary, $meta );
		if ( false === $saved ) {
			return new \WP_Error( 'cpais_review_save_failed', __( 'Could not save review summary.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 500 ) );
		}
		return rest_ensure_response( array( 'success' => true, 'length' => $saved ) );
	}

	public function get_review_summary( \WP_REST_Request $request ) {
		$product_id = absint( $request->get_param( 'product_id' ) );
		if ( ! $product_id ) {
			return new \WP_Error( 'cpais_invalid_product', __( 'Product not found.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 404 ) );
		}
		return rest_ensure_response( Review::get( $product_id ) );
	}

	public function generate_image_variants( \WP_REST_Request $request ) {
		$consent = $this->require_consent();
		if ( is_wp_error( $consent ) ) {
			return $consent;
		}
		$product = $this->get_product_from_request( $request );
		if ( is_wp_error( $product ) ) {
			return $product;
		}
		$params   = $request->get_json_params() ?: $request->get_params();
		$settings = array_merge( Settings::get_all(), $params );
		if ( empty( $settings['image_provider'] ) ) {
			$settings['image_provider'] = $settings['active_image_provider'] ?? 'openai';
		}
		$result = Generator::run_image_variants( $product, $settings );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return rest_ensure_response( $result );
	}

	public function remove_background( \WP_REST_Request $request ) {
		$consent = $this->require_consent();
		if ( is_wp_error( $consent ) ) {
			return $consent;
		}
		$params        = $request->get_json_params() ?: $request->get_params();
		$attachment_id = absint( $params['attachment_id'] ?? 0 );
		$product_id    = absint( $params['product_id'] ?? 0 );
		$attach_as     = sanitize_key( $params['attach_as'] ?? '' );

		if ( ! $attachment_id ) {
			return new \WP_Error( 'cpais_invalid_attachment', __( 'Attachment ID required.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 400 ) );
		}

		$settings = Settings::get_all();
		$api_key  = (string) ( $settings['image_replicate_api_key'] ?? '' );
		$model    = (string) ( $settings['bg_remover_model'] ?? '851-labs/background-remover' );

		$result = Media::remove_background( $attachment_id, $api_key, $model, $product_id, $attach_as );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return rest_ensure_response( $result );
	}

	public function export_settings() {
		$settings = Settings::get_all();
		// Strip encrypted API keys from export — user must re-enter.
		foreach ( Settings::key_fields() as $field ) {
			unset( $settings[ $field ] );
		}
		return rest_ensure_response(
			array(
				'version'  => CPAIS_VERSION,
				'exported' => gmdate( 'c' ),
				'settings' => $settings,
			)
		);
	}

	public function import_settings( \WP_REST_Request $request ) {
		$params = $request->get_json_params() ?: $request->get_params();
		if ( empty( $params['settings'] ) || ! is_array( $params['settings'] ) ) {
			return new \WP_Error( 'cpais_invalid_import', __( 'Invalid import payload.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 400 ) );
		}
		// Never allow raw API keys via import — must be re-entered.
		foreach ( Settings::key_fields() as $field ) {
			unset( $params['settings'][ $field ] );
		}
		Settings::update( $params['settings'] );
		return rest_ensure_response( array( 'success' => true ) );
	}

	public function apply_taxonomy( \WP_REST_Request $request ) {
		$params      = $request->get_json_params() ?: $request->get_params();
		$term_id     = absint( $params['term_id'] ?? 0 );
		$taxonomy    = sanitize_key( $params['taxonomy'] ?? 'product_cat' );
		$description = (string) ( $params['description'] ?? '' );

		$result = Generator::apply_taxonomy_description( $term_id, $taxonomy, $description );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		return rest_ensure_response( array( 'success' => true ) );
	}

	public function generate_tags( \WP_REST_Request $request ) {
		$product = $this->get_product_from_request( $request );
		if ( is_wp_error( $product ) ) { return $product; }
		$settings = Settings::get_all();
		$params   = $request->get_json_params() ?: $request->get_params();
		if ( isset( $params['tag_count'] ) ) {
			$settings['tag_count'] = absint( $params['tag_count'] );
		}
		$result = Generator::run_tags( $product, $settings );
		return is_wp_error( $result ) ? $result : rest_ensure_response( $result );
	}

	public function apply_tags( \WP_REST_Request $request ) {
		$product = $this->get_product_from_request( $request );
		if ( is_wp_error( $product ) ) { return $product; }
		$params = $request->get_json_params() ?: $request->get_params();
		$tags   = is_array( $params['tags'] ?? null ) ? $params['tags'] : array();
		$result = Generator::apply_tags( $product, $tags );
		return is_wp_error( $result ) ? $result : rest_ensure_response( $result );
	}

	public function generate_attributes( \WP_REST_Request $request ) {
		$product = $this->get_product_from_request( $request );
		if ( is_wp_error( $product ) ) { return $product; }
		$settings = Settings::get_all();
		$params   = $request->get_json_params() ?: $request->get_params();
		if ( isset( $params['attribute_count'] ) ) {
			$settings['attribute_count'] = absint( $params['attribute_count'] );
		}
		$result = Generator::run_attributes( $product, $settings );
		return is_wp_error( $result ) ? $result : rest_ensure_response( $result );
	}

	public function apply_attributes( \WP_REST_Request $request ) {
		$product = $this->get_product_from_request( $request );
		if ( is_wp_error( $product ) ) { return $product; }
		$params = $request->get_json_params() ?: $request->get_params();
		$attrs  = is_array( $params['attributes'] ?? null ) ? $params['attributes'] : array();
		$result = Generator::apply_attributes( $product, $attrs );
		return is_wp_error( $result ) ? $result : rest_ensure_response( $result );
	}

	public function generate_variation_description( \WP_REST_Request $request ) {
		$params       = $request->get_json_params() ?: $request->get_params();
		$variation_id = absint( $params['variation_id'] ?? 0 );
		$variation    = $variation_id ? wc_get_product( $variation_id ) : null;
		if ( ! $variation || ! ( $variation instanceof \WC_Product_Variation ) ) {
			return new \WP_Error( 'cpais_invalid_variation', __( 'Variation not found.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 404 ) );
		}
		$settings = Settings::get_all();
		if ( isset( $params['variation_words'] ) ) {
			$settings['variation_words'] = absint( $params['variation_words'] );
		}
		$result = Generator::run_variation_description( $variation, $settings );
		return is_wp_error( $result ) ? $result : rest_ensure_response( $result );
	}

	public function apply_variation_description( \WP_REST_Request $request ) {
		$params       = $request->get_json_params() ?: $request->get_params();
		$variation_id = absint( $params['variation_id'] ?? 0 );
		$description  = (string) ( $params['description'] ?? '' );
		if ( ! current_user_can( 'edit_post', $variation_id ) ) {
			return new \WP_Error( 'cpais_forbidden', __( 'Not allowed to edit this variation.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 403 ) );
		}
		$result = Generator::apply_variation_description( $variation_id, $description );
		return is_wp_error( $result ) ? $result : rest_ensure_response( $result );
	}

	private function get_product_from_request( \WP_REST_Request $request ) {
		$params     = $request->get_json_params() ?: $request->get_params();
		$product_id = absint( $params['product_id'] ?? 0 );
		$product    = $product_id ? wc_get_product( $product_id ) : null;
		if ( ! $product ) {
			return new \WP_Error( 'cpais_invalid_product', __( 'Product not found.', 'catalogpilot-ai-studio-for-woocommerce' ), array( 'status' => 404 ) );
		}
		return $product;
	}

	public static function option_definitions() {
		$variant_defs = Generator::image_variant_definitions();
		$variants     = array();
		foreach ( $variant_defs as $key => $def ) {
			$variants[] = array( 'value' => $key, 'label' => $def['label'] );
		}
		return array(
			'providers'       => Providers\cpais_text_providers_definitions(),
			'image_providers' => Providers\cpais_image_providers_definitions(),
			'image_variants'  => $variants,
			'image_styles'    => array(
				array( 'value' => 'studio',         'label' => __( 'Studio', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'lifestyle',      'label' => __( 'Lifestyle', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'flatlay',        'label' => __( 'Flat lay', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'artistic',       'label' => __( 'Artistic', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'transparent',    'label' => __( 'Transparent background', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'hero_shot',      'label' => __( 'Hero shot', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'feature_detail', 'label' => __( 'Feature detail', 'catalogpilot-ai-studio-for-woocommerce' ) ),
			),
			'image_attach' => array(
				array( 'value' => 'none',     'label' => __( 'Do not attach', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'featured', 'label' => __( 'Set as featured', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'gallery',  'label' => __( 'Add to gallery', 'catalogpilot-ai-studio-for-woocommerce' ) ),
			),
			'tones' => array(
				array( 'value' => 'professional', 'label' => __( 'Professional', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'friendly',     'label' => __( 'Friendly', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'technical',    'label' => __( 'Technical', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'seo',          'label' => __( 'SEO-focused', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'sales',        'label' => __( 'Sales-focused', 'catalogpilot-ai-studio-for-woocommerce' ) ),
			),
			'lengths' => array(
				array( 'value' => 'short',  'label' => __( 'Short', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'medium', 'label' => __( 'Medium', 'catalogpilot-ai-studio-for-woocommerce' ) ),
				array( 'value' => 'long',   'label' => __( 'Long', 'catalogpilot-ai-studio-for-woocommerce' ) ),
			),
			'languages' => array(
				array( 'value' => 'en', 'label' => 'English' ),
				array( 'value' => 'tr', 'label' => 'Türkçe' ),
				array( 'value' => 'de', 'label' => 'Deutsch' ),
				array( 'value' => 'es', 'label' => 'Español' ),
				array( 'value' => 'fr', 'label' => 'Français' ),
				array( 'value' => 'it', 'label' => 'Italiano' ),
				array( 'value' => 'ar', 'label' => 'العربية' ),
				array( 'value' => 'ru', 'label' => 'Русский' ),
			),
		);
	}
}
