<?php
/**
 * Settings Page Class
 *
 * Manages settings page functionality
 *
 * @package SmartyPress_AI_Engine
 * @since 1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Settings Page class
 */
class SmartyPress_AI_Settings_Page {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Register REST API routes
		add_action( 'rest_api_init', array( $this, 'register_rest_routes' ), 10 );
	}

	/**
	 * Register REST API routes
	 */
	public function register_rest_routes() {
		// Get settings
		register_rest_route(
			'smartypress/v1',
			'/settings',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_settings' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);

		// Update settings
		register_rest_route(
			'smartypress/v1',
			'/settings',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'update_settings' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);

		// Test provider
		register_rest_route(
			'smartypress/v1',
			'/settings/test-provider',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'test_provider' ),
				'permission_callback' => array( $this, 'check_permissions' ),
				'args'                => array(
					'provider' => array(
						'required' => true,
						'type'     => 'string',
					),
				),
			)
		);

		// Get provider models
		register_rest_route(
			'smartypress/v1',
			'/provider-models',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_provider_models' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);

		// Get all OpenRouter image models for settings screen.
		register_rest_route(
			'smartypress/v1',
			'/openrouter-image-models',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_openrouter_image_models' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);

		// Get logs
		register_rest_route(
			'smartypress/v1',
			'/logs',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_logs' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);

		// Clear logs
		register_rest_route(
			'smartypress/v1',
			'/logs',
			array(
				'methods'             => 'DELETE',
				'callback'            => array( $this, 'clear_logs' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);

		// Get log count
		register_rest_route(
			'smartypress/v1',
			'/logs/count',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_log_count' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);

		// Get available post types
		register_rest_route(
			'smartypress/v1',
			'/post-types',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_post_types' ),
				'permission_callback' => array( $this, 'check_permissions' ),
			)
		);
	}

	/**
	 * Get available post types for the plugin
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function get_post_types( $request ) {
		$post_types = get_post_types(
			array(
				'public'  => true,
				'show_ui' => true,
			),
			'objects'
		);

		$result = array();
		foreach ( $post_types as $post_type ) {
			// Skip attachments
			if ( $post_type->name === 'attachment' ) {
				continue;
			}

			$result[] = array(
				'name'  => $post_type->name,
				'label' => $post_type->labels->singular_name,
			);
		}

		return rest_ensure_response( $result );
	}

	/**
	 * Get available models for all providers
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function get_provider_models( $request ) {
		$provider_models = array(
			'openai'     => SmartyPress_AI_Model_Map::get_text_models( 'openai' ),
			'deepseek'   => SmartyPress_AI_Model_Map::get_text_models( 'deepseek' ),
			'anthropic'  => SmartyPress_AI_Model_Map::get_text_models( 'anthropic' ),
			'openrouter' => SmartyPress_AI_Model_Map::get_text_models( 'openrouter' ),
		);

		if ( get_locale() === 'ru_RU' ) {
			$provider_models['yandex']   = SmartyPress_AI_Model_Map::get_text_models( 'yandex' );
			$provider_models['gigachat'] = SmartyPress_AI_Model_Map::get_text_models( 'gigachat' );
		}

		return rest_ensure_response( $provider_models );
	}

	/**
	 * Get full OpenRouter image model list.
	 *
	 * This endpoint is used by Settings so selected filters do not hide
	 * unchecked models from the configuration screen.
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function get_openrouter_image_models( $request ) {
		return rest_ensure_response( SmartyPress_AI_Model_Map::get_image_models( 'openrouter' ) );
	}

	/**
	 * Get settings
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function get_settings( $request ) {
		$settings = get_option( 'smartypress_ai_settings', array() );
		$settings = $this->add_default_prompt_variables( $settings );
		$settings['openrouter_limit_text_models']  = ! empty( $settings['openrouter_limit_text_models'] );
		$settings['openrouter_limit_image_models'] = ! empty( $settings['openrouter_limit_image_models'] );

		// Don't expose API keys in full
		$safe_settings = $settings;
		if ( isset( $safe_settings['openai_api_key'] ) ) {
			$safe_settings['openai_api_key'] = $this->mask_api_key( $safe_settings['openai_api_key'] );
		}
		if ( isset( $safe_settings['deepseek_api_key'] ) ) {
			$safe_settings['deepseek_api_key'] = $this->mask_api_key( $safe_settings['deepseek_api_key'] );
		}
		if ( isset( $safe_settings['anthropic_api_key'] ) ) {
			$safe_settings['anthropic_api_key'] = $this->mask_api_key( $safe_settings['anthropic_api_key'] );
		}
		if ( isset( $safe_settings['openrouter_api_key'] ) ) {
			$safe_settings['openrouter_api_key'] = $this->mask_api_key( $safe_settings['openrouter_api_key'] );
		}
		if ( isset( $safe_settings['yandex_api_key'] ) ) {
			$safe_settings['yandex_api_key'] = $this->mask_api_key( $safe_settings['yandex_api_key'] );
		}
		if ( isset( $safe_settings['gigachat_auth_key'] ) ) {
			$safe_settings['gigachat_auth_key'] = $this->mask_api_key( $safe_settings['gigachat_auth_key'] );
		}

		return rest_ensure_response( $safe_settings );
	}

	/**
	 * Update settings
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function update_settings( $request ) {
		$settings = $request->get_json_params();

		// Sanitize settings
		$sanitized_settings = $this->sanitize_settings( $settings );

		// Get current settings
		$current_settings = get_option( 'smartypress_ai_settings', array() );

		// Merge with current settings
		$updated_settings = array_merge( $current_settings, $sanitized_settings );

		// If API key is masked (contains ***), don't update it - keep the original key
		if ( isset( $settings['openai_api_key'] ) && strpos( $settings['openai_api_key'], '***' ) !== false ) {
			$updated_settings['openai_api_key'] = $current_settings['openai_api_key'] ?? '';
		}
		if ( isset( $settings['deepseek_api_key'] ) && strpos( $settings['deepseek_api_key'], '***' ) !== false ) {
			$updated_settings['deepseek_api_key'] = $current_settings['deepseek_api_key'] ?? '';
		}
		if ( isset( $settings['anthropic_api_key'] ) && strpos( $settings['anthropic_api_key'], '***' ) !== false ) {
			$updated_settings['anthropic_api_key'] = $current_settings['anthropic_api_key'] ?? '';
		}
		if ( isset( $settings['openrouter_api_key'] ) && strpos( $settings['openrouter_api_key'], '***' ) !== false ) {
			$updated_settings['openrouter_api_key'] = $current_settings['openrouter_api_key'] ?? '';
		}
		if ( isset( $settings['yandex_api_key'] ) && strpos( $settings['yandex_api_key'], '***' ) !== false ) {
			$updated_settings['yandex_api_key'] = $current_settings['yandex_api_key'] ?? '';
		}
		if ( isset( $settings['gigachat_auth_key'] ) && strpos( $settings['gigachat_auth_key'], '***' ) !== false ) {
			$updated_settings['gigachat_auth_key'] = $current_settings['gigachat_auth_key'] ?? '';
		}

		// Save settings
		$result = update_option( 'smartypress_ai_settings', $updated_settings );

		if ( $result ) {
			// Reinitialize providers with new settings
			SmartyPress_AI_Providers::init( $updated_settings );
		}

		return rest_ensure_response(
			array(
				'success' => $result,
				'settings' => $updated_settings,
			)
		);
	}

	/**
	 * Test provider
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response|WP_Error
	 */
	public function test_provider( $request ) {
		$provider_name = $request->get_param( 'provider' );
		$settings      = get_option( 'smartypress_ai_settings', array() );

		$provider = SmartyPress_AI_Providers::get_provider( $provider_name );

		if ( ! $provider ) {
			return new WP_Error( 'provider_not_found', __( 'Provider not found or not configured', 'smartypress-ai-engine' ), array( 'status' => 404 ) );
		}

		// Test with a simple request using generate_content method
		try {
			$test_result = $provider->generate_content( 'Test', array( 'max_tokens' => 10 ) );
			
			if ( isset( $test_result['success'] ) && $test_result['success'] ) {
				return rest_ensure_response(
					array(
						'success' => true,
						'message' => __( 'Provider connection successful', 'smartypress-ai-engine' ),
					)
				);
			} else {
				$error_message = $test_result['error'] ?? __( 'Provider test failed', 'smartypress-ai-engine' );
				return new WP_Error( 'provider_test_failed', $error_message, array( 'status' => 500 ) );
			}
		} catch ( Exception $e ) {
			return new WP_Error( 'provider_test_failed', $e->getMessage(), array( 'status' => 500 ) );
		}
	}

	/**
	 * Sanitize settings before saving
	 *
	 * @param array $settings Raw settings from request.
	 * @return array Sanitized settings.
	 */
	private function sanitize_settings( $settings ) {
		$sanitized = array();

		// API keys
		if ( isset( $settings['openai_api_key'] ) ) {
			$sanitized['openai_api_key'] = sanitize_text_field( $settings['openai_api_key'] );
		}
		if ( isset( $settings['deepseek_api_key'] ) ) {
			$sanitized['deepseek_api_key'] = sanitize_text_field( $settings['deepseek_api_key'] );
		}
		if ( isset( $settings['openrouter_api_key'] ) ) {
			$sanitized['openrouter_api_key'] = sanitize_text_field( $settings['openrouter_api_key'] );
		}
		if ( isset( $settings['anthropic_api_key'] ) ) {
			$sanitized['anthropic_api_key'] = sanitize_text_field( $settings['anthropic_api_key'] );
		}
		if ( isset( $settings['openrouter_model'] ) ) {
			$sanitized['openrouter_model'] = sanitize_text_field( $settings['openrouter_model'] );
		}
		if ( isset( $settings['openrouter_image_model'] ) ) {
			$sanitized['openrouter_image_model'] = sanitize_text_field( $settings['openrouter_image_model'] );
		}
		if ( array_key_exists( 'openrouter_limit_text_models', $settings ) ) {
			$sanitized['openrouter_limit_text_models'] = (bool) $settings['openrouter_limit_text_models'];
		}
		if ( isset( $settings['openrouter_enabled_text_models'] ) && is_array( $settings['openrouter_enabled_text_models'] ) ) {
			$sanitized['openrouter_enabled_text_models'] = array_values( array_filter( array_map( 'sanitize_text_field', $settings['openrouter_enabled_text_models'] ) ) );
		}
		if ( array_key_exists( 'openrouter_limit_image_models', $settings ) ) {
			$sanitized['openrouter_limit_image_models'] = (bool) $settings['openrouter_limit_image_models'];
		}
		if ( isset( $settings['openrouter_enabled_image_models'] ) && is_array( $settings['openrouter_enabled_image_models'] ) ) {
			$sanitized['openrouter_enabled_image_models'] = array_values( array_filter( array_map( 'sanitize_text_field', $settings['openrouter_enabled_image_models'] ) ) );
		}
		if ( isset( $settings['yandex_api_key'] ) ) {
			$sanitized['yandex_api_key'] = sanitize_text_field( $settings['yandex_api_key'] );
		}
		if ( isset( $settings['yandex_folder_id'] ) ) {
			$sanitized['yandex_folder_id'] = sanitize_text_field( $settings['yandex_folder_id'] );
		}

		// GigaChat settings
		if ( isset( $settings['gigachat_auth_key'] ) ) {
			$sanitized['gigachat_auth_key'] = sanitize_text_field( $settings['gigachat_auth_key'] );
		}
		if ( isset( $settings['gigachat_scope'] ) ) {
			$allowed_scopes = array( 'GIGACHAT_API_PERS', 'GIGACHAT_API_B2B', 'GIGACHAT_API_CORP' );
			$scope = sanitize_text_field( $settings['gigachat_scope'] );
			$sanitized['gigachat_scope'] = in_array( $scope, $allowed_scopes, true ) ? $scope : 'GIGACHAT_API_PERS';
		}
		if ( isset( $settings['gigachat_base_url'] ) ) {
			$allowed_base_urls = array(
				'https://gigachat.devices.sberbank.ru/api/v1',
				'https://api.giga.chat/v1',
			);
			$base_url = untrailingslashit( esc_url_raw( $settings['gigachat_base_url'] ) );
			$sanitized['gigachat_base_url'] = in_array( $base_url, $allowed_base_urls, true ) ? $base_url : 'https://gigachat.devices.sberbank.ru/api/v1';
		}
		if ( isset( $settings['gigachat_model'] ) ) {
			$sanitized['gigachat_model'] = sanitize_text_field( $settings['gigachat_model'] );
		}
		if ( isset( $settings['gigachat_verify_ssl'] ) ) {
			$sanitized['gigachat_verify_ssl'] = (bool) $settings['gigachat_verify_ssl'];
		}

		if ( isset( $settings['provider_connection_status'] ) && is_array( $settings['provider_connection_status'] ) ) {
			$allowed_providers = array( 'openai', 'deepseek', 'anthropic', 'openrouter', 'yandex', 'gigachat' );
			$sanitized['provider_connection_status'] = array();

			foreach ( $settings['provider_connection_status'] as $provider_id => $is_connected ) {
				$provider_id = sanitize_key( $provider_id );

				if ( in_array( $provider_id, $allowed_providers, true ) ) {
					$sanitized['provider_connection_status'][ $provider_id ] = (bool) $is_connected;
				}
			}
		}

		if ( isset( $settings['prompt_variables'] ) && is_array( $settings['prompt_variables'] ) ) {
			$prompt_variables = wp_parse_args(
				$settings['prompt_variables'],
				$this->get_default_prompt_variables()
			);

			$sanitized['prompt_variables'] = array(
				'writing_tone'           => sanitize_text_field( $prompt_variables['writing_tone'] ),
				'writing_style'          => sanitize_text_field( $prompt_variables['writing_style'] ),
				'number_of_sections'     => max( 1, absint( $prompt_variables['number_of_sections'] ) ),
				'paragraphs_per_section' => max( 1, absint( $prompt_variables['paragraphs_per_section'] ) ),
			);

			foreach ( $prompt_variables as $key => $value ) {
				$key = sanitize_key( $key );

				if ( '' === $key || isset( $sanitized['prompt_variables'][ $key ] ) ) {
					continue;
				}

				$sanitized['prompt_variables'][ $key ] = sanitize_text_field( $value );
			}
		}

		// Providers and models - validate that default_provider has an API key configured
		if ( isset( $settings['default_provider'] ) ) {
			$provider = $settings['default_provider'];
			$has_key = false;

			// Check if selected provider has an API key (not masked - no *** in the string)
			if ( $provider === 'openai' && ! empty( $settings['openai_api_key'] ) && strpos( $settings['openai_api_key'], '***' ) === false ) {
				$has_key = true;
			} elseif ( $provider === 'openai' && ! empty( $sanitized['openai_api_key'] ) ) {
				$has_key = true;
			} elseif ( $provider === 'deepseek' && ! empty( $settings['deepseek_api_key'] ) && strpos( $settings['deepseek_api_key'], '***' ) === false ) {
				$has_key = true;
			} elseif ( $provider === 'deepseek' && ! empty( $sanitized['deepseek_api_key'] ) ) {
				$has_key = true;
			} elseif ( $provider === 'anthropic' && ! empty( $settings['anthropic_api_key'] ) && strpos( $settings['anthropic_api_key'], '***' ) === false ) {
				$has_key = true;
			} elseif ( $provider === 'anthropic' && ! empty( $sanitized['anthropic_api_key'] ) ) {
				$has_key = true;
			} elseif ( $provider === 'openrouter' && ! empty( $settings['openrouter_api_key'] ) && strpos( $settings['openrouter_api_key'], '***' ) === false ) {
				$has_key = true;
			} elseif ( $provider === 'openrouter' && ! empty( $sanitized['openrouter_api_key'] ) ) {
				$has_key = true;
			} elseif ( $provider === 'yandex' && ! empty( $settings['yandex_api_key'] ) && strpos( $settings['yandex_api_key'], '***' ) === false && ! empty( $settings['yandex_folder_id'] ) ) {
				$has_key = true;
			} elseif ( $provider === 'yandex' && ! empty( $sanitized['yandex_api_key'] ) && ! empty( $sanitized['yandex_folder_id'] ) ) {
				$has_key = true;
			} elseif ( $provider === 'gigachat' && ! empty( $settings['gigachat_auth_key'] ) && strpos( $settings['gigachat_auth_key'], '***' ) === false ) {
				$has_key = true;
			} elseif ( $provider === 'gigachat' && ! empty( $sanitized['gigachat_auth_key'] ) ) {
				$has_key = true;
			}

			// Also check current settings for masked keys (already saved)
			$current_settings = get_option( 'smartypress_ai_settings', array() );
			if ( ! $has_key && $provider === 'openai' && ! empty( $current_settings['openai_api_key'] ) ) {
				$has_key = true;
			}
			if ( ! $has_key && $provider === 'deepseek' && ! empty( $current_settings['deepseek_api_key'] ) ) {
				$has_key = true;
			}
			if ( ! $has_key && $provider === 'anthropic' && ! empty( $current_settings['anthropic_api_key'] ) ) {
				$has_key = true;
			}
			if ( ! $has_key && $provider === 'openrouter' && ! empty( $current_settings['openrouter_api_key'] ) ) {
				$has_key = true;
			}
			if ( ! $has_key && $provider === 'yandex' && ! empty( $current_settings['yandex_api_key'] ) && ! empty( $current_settings['yandex_folder_id'] ) ) {
				$has_key = true;
			}
			if ( ! $has_key && $provider === 'gigachat' && ! empty( $current_settings['gigachat_auth_key'] ) ) {
				$has_key = true;
			}

			if ( $has_key ) {
				$sanitized['default_provider'] = $provider;
			} else {
				// Fall back to first available provider with API key (not masked - no *** in the string)
				if ( ! empty( $current_settings['deepseek_api_key'] ) || ( ! empty( $settings['deepseek_api_key'] ) && strpos( $settings['deepseek_api_key'], '***' ) === false ) ) {
					$sanitized['default_provider'] = 'deepseek';
				} elseif ( ! empty( $current_settings['anthropic_api_key'] ) || ( ! empty( $settings['anthropic_api_key'] ) && strpos( $settings['anthropic_api_key'], '***' ) === false ) ) {
					$sanitized['default_provider'] = 'anthropic';
				} elseif ( ! empty( $current_settings['openrouter_api_key'] ) || ( ! empty( $settings['openrouter_api_key'] ) && strpos( $settings['openrouter_api_key'], '***' ) === false ) ) {
					$sanitized['default_provider'] = 'openrouter';
				} elseif ( ! empty( $current_settings['openai_api_key'] ) || ( ! empty( $settings['openai_api_key'] ) && strpos( $settings['openai_api_key'], '***' ) === false ) ) {
					$sanitized['default_provider'] = 'openai';
				} elseif ( ( ! empty( $current_settings['yandex_api_key'] ) && ! empty( $current_settings['yandex_folder_id'] ) ) || ( ! empty( $settings['yandex_api_key'] ) && strpos( $settings['yandex_api_key'], '***' ) === false && ! empty( $settings['yandex_folder_id'] ) ) ) {
					$sanitized['default_provider'] = 'yandex';
				} elseif ( ! empty( $current_settings['gigachat_auth_key'] ) || ( ! empty( $settings['gigachat_auth_key'] ) && strpos( $settings['gigachat_auth_key'], '***' ) === false ) ) {
					$sanitized['default_provider'] = 'gigachat';
				} else {
					$sanitized['default_provider'] = '';
				}
			}
		}

		if ( isset( $settings['default_model'] ) ) {
			$sanitized['default_model'] = sanitize_text_field( $settings['default_model'] );
		}

		// Provider-specific models
		if ( isset( $settings['openai_model'] ) ) {
			$sanitized['openai_model'] = sanitize_text_field( $settings['openai_model'] );
		}
		if ( isset( $settings['deepseek_model'] ) ) {
			$sanitized['deepseek_model'] = sanitize_text_field( $settings['deepseek_model'] );
		}
		if ( isset( $settings['anthropic_model'] ) ) {
			$sanitized['anthropic_model'] = sanitize_text_field( $settings['anthropic_model'] );
		}
		if ( isset( $settings['yandex_model'] ) ) {
			$sanitized['yandex_model'] = sanitize_text_field( $settings['yandex_model'] );
		}

		// OpenAI Proxy settings
		if ( isset( $settings['openai_use_proxy'] ) ) {
			$sanitized['openai_use_proxy'] = (bool) $settings['openai_use_proxy'];
		}
		if ( isset( $settings['openai_proxy_url'] ) ) {
			$sanitized['openai_proxy_url'] = sanitize_text_field( $settings['openai_proxy_url'] );
		}

		// Default language
		if ( isset( $settings['default_language'] ) ) {
			$allowed_languages = array(
				'English', 'Russian', 'German', 'French', 'Spanish', 'Italian', 'Portuguese',
				'Chinese', 'Japanese', 'Korean', 'Arabic', 'Dutch', 'Polish', 'Turkish',
				'Ukrainian', 'Hindi', 'Indonesian', 'Vietnamese',
			);
			$language = sanitize_text_field( $settings['default_language'] );
			$sanitized['default_language'] = in_array( $language, $allowed_languages, true )
				? $language
				: '';
		}

		// Numeric parameters
		if ( isset( $settings['temperature'] ) ) {
			$sanitized['temperature'] = floatval( $settings['temperature'] );
			$sanitized['temperature'] = max( 0, min( 2, $sanitized['temperature'] ) ); // 0-2 range
		}

		if ( isset( $settings['max_tokens'] ) ) {
			$sanitized['max_tokens'] = absint( $settings['max_tokens'] );
			$sanitized['max_tokens'] = max( 1, min( 32000, $sanitized['max_tokens'] ) );
		}

		// Modules (boolean and nested settings)
		if ( isset( $settings['modules'] ) && is_array( $settings['modules'] ) ) {
			$sanitized['modules'] = array();
			foreach ( $settings['modules'] as $module_id => $module_settings ) {
				$module_id = sanitize_key( $module_id );
				if ( is_array( $module_settings ) ) {
					$sanitized['modules'][ $module_id ] = array();
					foreach ( $module_settings as $key => $value ) {
						$key = sanitize_key( $key );
						if ( $key === 'enabled' ) {
							$sanitized['modules'][ $module_id ][ $key ] = (bool) $value;
						} else {
							$sanitized['modules'][ $module_id ][ $key ] = sanitize_text_field( $value );
						}
					}
				}
			}
		}

		// Debug settings
		if ( isset( $settings['enable_debug'] ) ) {
			$sanitized['enable_debug'] = (bool) $settings['enable_debug'];
		}

		if ( isset( $settings['log_successful_requests'] ) ) {
			$sanitized['log_successful_requests'] = (bool) $settings['log_successful_requests'];
		}

		// Enabled post types
		if ( isset( $settings['enabled_post_types'] ) && is_array( $settings['enabled_post_types'] ) ) {
			$sanitized['enabled_post_types'] = array_map( 'sanitize_key', $settings['enabled_post_types'] );
		}

		return $sanitized;
	}

	/**
	 * Get default prompt variables.
	 *
	 * @return array
	 */
	private function get_default_prompt_variables() {
		return array(
			'writing_tone'           => 'neutral',
			'writing_style'          => 'informative',
			'number_of_sections'     => '3',
			'paragraphs_per_section' => '3',
		);
	}

	/**
	 * Ensure prompt variables exist in settings response.
	 *
	 * @param array $settings Plugin settings.
	 * @return array
	 */
	private function add_default_prompt_variables( $settings ) {
		$settings['prompt_variables'] = wp_parse_args(
			$settings['prompt_variables'] ?? array(),
			$this->get_default_prompt_variables()
		);

		return $settings;
	}

	/**
	 * Mask API key for display
	 *
	 * @param string $api_key API key.
	 * @return string Masked API key.
	 */
	private function mask_api_key( $api_key ) {
		if ( empty( $api_key ) ) {
			return '';
		}
		$length = strlen( $api_key );
		if ( $length <= 8 ) {
			return '***';
		}
		return substr( $api_key, 0, 4 ) . '***' . substr( $api_key, -4 );
	}

	/**
	 * Check permissions
	 *
	 * @return bool
	 */
	public function check_permissions() {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Get logs
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function get_logs( $request ) {
		if ( ! class_exists( 'SmartyPress_AI_Logger' ) ) {
			return rest_ensure_response( array() );
		}

		$limit = $request->get_param( 'limit' );
		$limit = $limit ? absint( $limit ) : 0;

		$logs = SmartyPress_AI_Logger::get_logs( $limit );

		return rest_ensure_response( $logs );
	}

	/**
	 * Clear logs
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function clear_logs( $request ) {
		if ( ! class_exists( 'SmartyPress_AI_Logger' ) ) {
			return rest_ensure_response(
				array(
					'success' => false,
					'message' => __( 'Logger not available', 'smartypress-ai-engine' ),
				)
			);
		}

		$result = SmartyPress_AI_Logger::clear_logs();

		return rest_ensure_response(
			array(
				'success' => $result,
				'message' => $result
					? __( 'Logs cleared successfully', 'smartypress-ai-engine' )
					: __( 'Failed to clear logs', 'smartypress-ai-engine' ),
			)
		);
	}

	/**
	 * Get log count
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return WP_REST_Response
	 */
	public function get_log_count( $request ) {
		if ( ! class_exists( 'SmartyPress_AI_Logger' ) ) {
			return rest_ensure_response( array( 'count' => 0 ) );
		}

		$count = SmartyPress_AI_Logger::get_log_count();

		return rest_ensure_response( array( 'count' => $count ) );
	}
}

