<?php
/**
 * REST API controller
 */
class Nietos_AI_REST_Controller {

    /**
     * API handler instance
     */
    private $api_handler;

    /**
     * Settings instance
     */
    private $settings;

    /**
     * Premium instance
     */
    private $premium;

    /**
     * Constructor
     */
    public function __construct($api_handler, $settings) {
        $this->api_handler = $api_handler;
        $this->settings = $settings;
        $this->premium = new Nietos_AI_Premium();
    }

    /**
     * Register REST routes
     */
    public function register_routes() {
        $namespace = 'nietos-ai/v1';

        // Chat endpoint
        register_rest_route($namespace, '/chat', array(
            'methods' => 'POST',
            'callback' => array($this, 'handle_chat'),
            'permission_callback' => array($this, 'check_permissions')
        ));

        // Execute WordPress operation
        register_rest_route($namespace, '/execute', array(
            'methods' => 'POST',
            'callback' => array($this, 'handle_execute'),
            'permission_callback' => array($this, 'check_permissions')
        ));

        // Get editor context
        register_rest_route($namespace, '/context', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_context'),
            'permission_callback' => array($this, 'check_permissions')
        ));

        // Settings endpoints
        register_rest_route($namespace, '/settings', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_settings'),
            'permission_callback' => array($this, 'check_admin_permissions')
        ));

        register_rest_route($namespace, '/settings', array(
            'methods' => 'POST',
            'callback' => array($this, 'update_settings'),
            'permission_callback' => array($this, 'check_admin_permissions')
        ));

        // Test connection
        register_rest_route($namespace, '/test-connection', array(
            'methods' => 'POST',
            'callback' => array($this, 'test_connection'),
            'permission_callback' => array($this, 'check_admin_permissions')
        ));

        // Premium status
        register_rest_route($namespace, '/premium-status', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_premium_status'),
            'permission_callback' => array($this, 'check_permissions')
        ));
    }

    /**
     * Handle chat message
     */
    public function handle_chat($request) {
        $params = $request->get_json_params();
        $messages = $params['messages'] ?? array();
        $context = $params['context'] ?? null;

        if (empty($messages)) {
            return new WP_Error('no_messages', __('No messages provided', 'nietos-ai'), array('status' => 400));
        }

        // Check message limit for free users
        if (!$this->premium->can_send_message()) {
            return new WP_Error(
                'message_limit_reached',
                sprintf(
                    /* translators: %d: free message limit per day */
                    __('You have reached the free limit of %d messages per day. Please upgrade to Premium for unlimited messages.', 'nietos-ai'),
                    Nietos_AI_Premium::FREE_MESSAGE_LIMIT
                ),
                array('status' => 403, 'premium_required' => true)
            );
        }

        if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
            error_log('=== Nietos AI: New chat request ===');
            error_log('Messages count: ' . count($messages));
        }

        // Get settings
        $settings = $this->settings->get_settings();
        $settings['api_key'] = $this->settings->get_setting('api_key');

        // Load system prompt
        $system_prompt = $this->load_system_prompt($context, $messages);

        // Add system prompt to messages
        array_unshift($messages, array(
            'role' => 'system',
            'content' => $system_prompt
        ));

        // Determine tool groups before requesting tools
        $tool_groups = $this->determine_tool_groups($messages);

        if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
            error_log('Tool groups: ' . implode(', ', $tool_groups));
        }

        // Get WordPress tools relevant to this request
        $tools = $this->get_wordpress_tools($messages, $tool_groups);

        if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
            error_log('Available tools count: ' . count($tools));
        }

        // Send to AI
        $response = $this->api_handler->send_message($messages, $settings, $tools);

        if (is_wp_error($response)) {
            if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
                error_log('ERROR: Initial API call failed: ' . $response->get_error_message());
            }
            return $response;
        }

        // Tool execution loop - handle multiple rounds of tool calls
        $max_iterations = 10; // Prevent infinite loops
        $iteration = 0;

        while ($iteration < $max_iterations) {
            // Check if OpenAI wants to call tools
            if (isset($response['choices'][0]['message']['tool_calls'])) {
                $tool_calls = $response['choices'][0]['message']['tool_calls'];
                $iteration++;

                if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
                    error_log("=== Tool Execution Round $iteration ===");
                    error_log('Tool calls requested: ' . count($tool_calls));
                }

                // Add assistant's tool call message to conversation
                $messages[] = array(
                    'role' => 'assistant',
                    'content' => null,
                    'tool_calls' => $tool_calls
                );

                // Execute each tool call and collect results
                foreach ($tool_calls as $index => $tool_call) {
                    $function_name = $tool_call['function']['name'];
                    $function_args = json_decode($tool_call['function']['arguments'], true);

                    if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
                        error_log("Tool " . ($index + 1) . "/$iteration: $function_name");
                        error_log('Arguments: ' . json_encode($function_args));
                    }

                    // Execute the function
                    $result = $this->execute_operation($function_name, $function_args);

                    // Log result (truncated if too long)
                    if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
                        $result_str = json_encode($result);
                        if (strlen($result_str) > 500) {
                            error_log('Result: ' . substr($result_str, 0, 500) . '... (truncated)');
                        } else {
                            error_log('Result: ' . $result_str);
                        }
                    }

                    // Add tool result to conversation
                    $messages[] = array(
                        'role' => 'tool',
                        'tool_call_id' => $tool_call['id'],
                        'content' => json_encode($result)
                    );
                }

                // Get next response from AI
                $next_tools = $this->get_wordpress_tools($messages, $tool_groups);
                $response = $this->api_handler->send_message($messages, $settings, $next_tools);

                if (is_wp_error($response)) {
                    if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
                        error_log("ERROR: Tool execution round $iteration failed: " . $response->get_error_message());
                    }
                    return $response;
                }
            } else {
                // No more tool calls, we have the final response
                if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
                    error_log('=== Final response received (after ' . $iteration . ' tool execution rounds) ===');
                }
                break;
            }
        }

        if ($iteration >= $max_iterations) {
            if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
                error_log('WARNING: Reached maximum tool execution iterations (' . $max_iterations . ')');
            }
        }

        // Ensure we have content in the final response
        if (empty($response['choices'][0]['message']['content'])) {
            if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
                error_log('WARNING: Final response has no content, adding fallback message');
            }
            $response['choices'][0]['message']['content'] = 'En saanut vahvistusta siitä, että toimenpide onnistui. Tarkista tilanne editorista ja pyydä tarvittaessa uusi yritys. Jos tarvitset apua WordPress-sivusi kanssa, ota yhteyttä: ville.toimela@gmail.com.';
        } else {
            if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
                $content_length = strlen($response['choices'][0]['message']['content']);
                error_log("Final response content length: $content_length characters");
            }
        }

        // Increment message count for free users
        $this->premium->increment_message_count();

        // Mark API key as validated on successful chat
        $this->settings->mark_api_key_validated();

        if (defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG) {
            error_log('=== Chat request completed ===');
        }
        return rest_ensure_response($response);
    }

    /**
     * Handle WordPress operation execution
     */
    public function handle_execute($request) {
        $params = $request->get_json_params();
        $operation = $params['operation'] ?? '';
        $args = $params['args'] ?? array();

        if (empty($operation)) {
            return new WP_Error('no_operation', __('No operation specified', 'nietos-ai'), array('status' => 400));
        }

        // Execute operation
        $result = $this->execute_operation($operation, $args);

        return rest_ensure_response($result);
    }

    /**
     * Get editor context
     */
    public function get_context($request) {
        $post_id = $request->get_param('post_id');

        if (!$post_id) {
            return new WP_Error('no_post_id', __('No post ID provided', 'nietos-ai'), array('status' => 400));
        }

        $post = get_post($post_id);

        if (!$post) {
            return new WP_Error('post_not_found', __('Post not found', 'nietos-ai'), array('status' => 404));
        }

        return rest_ensure_response(array(
            'post_id' => $post->ID,
            'post_title' => $post->post_title,
            'post_type' => $post->post_type,
            'post_status' => $post->post_status,
            'post_content' => $post->post_content
        ));
    }

    /**
     * Get settings
     */
    public function get_settings($request) {
        $settings = $this->settings->get_settings();

        // Don't send encrypted API key to frontend
        $settings['api_key'] = !empty($settings['api_key']) ? '••••••••' : '';
        $settings['has_api_key'] = $this->settings->is_configured();

        return rest_ensure_response($settings);
    }

    /**
     * Update settings
     */
    public function update_settings($request) {
        $params = $request->get_json_params();

        $result = $this->settings->update_settings($params);

        if ($result) {
            return rest_ensure_response(array(
                'success' => true,
                'message' => __('Settings updated successfully', 'nietos-ai')
            ));
        }

        return new WP_Error('update_failed', __('Failed to update settings', 'nietos-ai'), array('status' => 500));
    }

    /**
     * Test API connection
     */
    public function test_connection($request) {
        $params = $request->get_json_params();
        $api_key = $params['api_key'] ?? '';
        $model = $params['model'] ?? '';

        if (empty($api_key)) {
            return new WP_Error('no_api_key', __('API key is required', 'nietos-ai'), array('status' => 400));
        }

        // Encrypt the key for testing
        $security = new Nietos_AI_Security();
        $encrypted_key = $security->encrypt_api_key($api_key);

        $result = $this->api_handler->test_connection($encrypted_key, $model);

        // Mark API key as validated if test was successful
        if (isset($result['success']) && $result['success'] === true) {
            $this->settings->mark_api_key_validated();
        }

        return rest_ensure_response($result);
    }

    /**
     * Get premium status and message limits
     */
    public function get_premium_status($request) {
        $has_premium = $this->premium->has_premium_license();
        $remaining = $this->premium->get_remaining_messages();
        $message_count = $this->premium->get_message_count();

        return rest_ensure_response(array(
            'has_premium' => $has_premium,
            'remaining_messages' => $remaining,
            'message_count' => $message_count,
            'message_limit' => Nietos_AI_Premium::FREE_MESSAGE_LIMIT,
            'license_key' => $this->premium->get_license_key_masked()
        ));
    }

    /**
     * Check permissions
     */
    public function check_permissions() {
        return current_user_can('edit_posts');
    }

    /**
     * Check admin permissions
     */
    public function check_admin_permissions() {
        return current_user_can('manage_options');
    }

    /**
     * Load system prompt with instructions
     */
    private function load_system_prompt($context = null, $messages = array()) {
        $prompts_dir = NIETOS_AI_PLUGIN_DIR . 'prompts/';

        $system_prompt = file_exists($prompts_dir . 'system-prompt.md')
            ? file_get_contents($prompts_dir . 'system-prompt.md')
            : $this->get_default_system_prompt();

        // Add context if editing a post
        if ($context && isset($context['post_id'])) {
            $system_prompt .= "\n\n## Current Context\n";
            $system_prompt .= "You are currently helping edit:\n";
            $system_prompt .= "- Post ID: {$context['post_id']}\n";
            $system_prompt .= "- Title: {$context['post_title']}\n";
            $system_prompt .= "- Type: {$context['post_type']}\n";
        }

        // Load operation instructions
        $instructions_dir = $prompts_dir . 'instructions/';
        $instruction_map = array(
            'core' => array('content.md'),
            'media' => array('media.md'),
            'users' => array('users.md'),
            'settings' => array('settings.md'),
            'taxonomy' => array('taxonomy.md'),
            'comments' => array('comments.md'),
            'widgets' => array('widgets.md'),
            'menus' => array('menus.md'),
            'plugins' => array('plugins.md')
        );

        $selected_groups = $this->determine_tool_groups($messages);
        $selected_files = array('content.md'); // Always include content guidelines

        $latest_instruction = $this->get_latest_user_instruction($messages);
        if ($latest_instruction) {
            $system_prompt .= "\n\n## Latest User Instruction\n" . $latest_instruction;
        }

        foreach ($selected_groups as $group) {
            if (isset($instruction_map[$group])) {
                $selected_files = array_merge($selected_files, $instruction_map[$group]);
            }
        }

        $selected_files = array_unique($selected_files);

        foreach ($selected_files as $file) {
            $file_path = $instructions_dir . $file;
            if (file_exists($file_path)) {
                $system_prompt .= "\n\n" . file_get_contents($file_path);
            }
        }

        // Apply filters to allow customization
        return apply_filters('nietos_ai_system_prompt', $system_prompt, $context);
    }

    /**
     * Get default system prompt (fallback if files don't exist)
     */
    private function get_default_system_prompt() {
        return "You are Nietos AI, an intelligent WordPress assistant.

CRITICAL RULES:
1. You MUST use the provided functions to perform actions - do NOT just describe or pretend to do them
2. NEVER claim you did something unless you actually called the function AND it succeeded
3. ALWAYS verify results with get_* functions after making changes

BLOCK PATTERNS WORKFLOW:
When creating landing pages or rich layouts:
1. Call list_block_patterns() first - never assume what patterns exist
2. Select 3-5 appropriate patterns from the results
3. Call apply_block_pattern() for each (first with mode='replace', rest with mode='append')
4. Call update_post_blocks() to customize placeholder text
5. Call get_post_blocks() to verify the changes
Never say 'I used patterns' without actually calling apply_block_pattern.

Available functions:
- list_block_patterns: List available block patterns (ALWAYS call first when using patterns)
- apply_block_pattern: Insert pattern to post (use exact 'name' from list, not title)
- create_post: Creates new posts/pages
- update_post: Updates existing posts/pages
- get_post_content: Retrieves current content and metadata for an existing post or page
- get_post_blocks: Summarises Gutenberg blocks for a post (call to VERIFY changes)
- update_post_blocks: Replaces or appends Gutenberg block markup
- find_posts: Searches for posts or pages matching a keyword
- find_media: Searches media library items
- delete_post: Deletes posts/pages
- list_terms: Lists taxonomy terms matching a filter
- list_post_revisions: Lists available revisions for a post or page
- restore_post_revision: Restores a previous revision of a post or page
- upload_media: Adds new media items from URLs
- update_media_metadata: Updates attachment titles, captions, and alt text
- set_featured_image: Assigns a media item as a post's featured image
- create_user: Creates new WordPress users
- update_user: Updates existing WordPress users
- change_user_role: Changes user roles with safety checks
- delete_user: Deletes users (with optional reassignment)
- update_site_settings: Updates core site settings (title, tagline, formats, timezone)
- update_discussion_settings: Updates key discussion/comment settings
- create_term: Creates taxonomy terms (categories, tags)
- update_term: Updates taxonomy terms
- delete_term: Deletes taxonomy terms (with confirmations)
- assign_terms_to_post: Assigns categories/tags to content
- approve_comment: Approves comments awaiting moderation
- trash_comment: Moves comments to trash (requires confirmation)
- reply_to_comment: Replies to an existing comment as the current user
- create_widget: Creates widget instances with optional sidebar assignment
- update_widget: Updates widget settings
- delete_widget: Deletes widgets and removes them from sidebars
- assign_widget_to_sidebar: Places widgets into specific sidebars
- create_menu: Creates navigation menus
- update_menu: Updates navigation menus
- delete_menu: Deletes navigation menus (with confirmation)
- add_menu_item: Adds items to navigation menus
- update_menu_item: Updates existing menu items
- delete_menu_item: Deletes menu items (with confirmation)
- assign_menu_location: Assigns menus to theme locations
- activate_plugin: Activates installed plugins
- deactivate_plugin: Deactivates active plugins (with confirmation)

Always call the actual functions when users request actions. Never pretend or roleplay.";
    }

    private function build_all_tools() {
        $tools = array(
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'create_post',
                    'description' => 'Create post or page',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'title' => array('type' => 'string'),
                            'content' => array('type' => 'string'),
                            'post_type' => array('type' => 'string', 'enum' => array('post', 'page'), 'default' => 'post'),
                            'status' => array('type' => 'string', 'enum' => array('draft', 'publish', 'pending'), 'default' => 'draft')
                        ),
                        'required' => array('title', 'content')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'update_post',
                    'description' => 'Update post fields',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'post_id' => array('type' => 'integer'),
                            'title' => array('type' => 'string'),
                            'content' => array('type' => 'string'),
                            'status' => array('type' => 'string', 'enum' => array('draft', 'publish', 'pending'))
                        ),
                        'required' => array('post_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'get_post_content',
                    'description' => 'Fetch post content',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'post_id' => array('type' => 'integer')
                        ),
                        'required' => array('post_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'get_post_blocks',
                    'description' => 'List Gutenberg blocks',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'post_id' => array('type' => 'integer'),
                            'include_html' => array('type' => 'boolean')
                        ),
                        'required' => array('post_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'update_post_blocks',
                    'description' => 'Write Gutenberg blocks',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'post_id' => array('type' => 'integer'),
                            'gutenberg_content' => array('type' => 'string'),
                            'blocks' => array('type' => 'array', 'items' => array('type' => 'object')),
                            'mode' => array('type' => 'string', 'enum' => array('replace', 'append', 'prepend'), 'default' => 'replace')
                        ),
                        'required' => array('post_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'list_block_patterns',
                    'description' => 'List all available block patterns from the active theme. ALWAYS call this FIRST before using patterns - never assume what patterns exist. Returns pattern names, titles, categories, and descriptions.',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'search' => array('type' => 'string', 'description' => 'Optional search term to filter patterns'),
                            'category' => array('type' => 'string', 'description' => 'Optional category to filter patterns (e.g., "featured", "banner", "call-to-action")'),
                            'limit' => array('type' => 'integer', 'minimum' => 1, 'maximum' => 50, 'description' => 'Maximum number of patterns to return (default: 20)')
                        )
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'apply_block_pattern',
                    'description' => 'Insert a block pattern into a post. Call list_block_patterns first to see available patterns. Can be called multiple times to build rich layouts. After applying, use update_post_blocks to customize placeholder text, then get_post_blocks to verify. IMPORTANT: Use the exact pattern "name" field from list_block_patterns, not the title.',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'post_id' => array('type' => 'integer', 'description' => 'Post ID to insert pattern into'),
                            'pattern_name' => array('type' => 'string', 'description' => 'Exact pattern name from list_block_patterns (e.g. "twentytwentyfive/banner-about-book", NOT the title)'),
                            'mode' => array('type' => 'string', 'enum' => array('append', 'prepend', 'replace'), 'default' => 'append', 'description' => 'Where to insert: replace=replace all content (use for first pattern), append=add to end (use for additional patterns), prepend=add to start')
                        ),
                        'required' => array('post_id', 'pattern_name')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'find_posts',
                    'description' => 'Search posts',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'search' => array('type' => 'string'),
                            'post_type' => array('type' => 'string'),
                            'status' => array('type' => 'string'),
                            'limit' => array('type' => 'integer', 'minimum' => 1, 'maximum' => 20)
                        )
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'list_post_revisions',
                    'description' => 'List revisions',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'post_id' => array('type' => 'integer'),
                            'limit' => array('type' => 'integer', 'minimum' => 1, 'maximum' => 20)
                        ),
                        'required' => array('post_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'find_media',
                    'description' => 'Search media library',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'search' => array('type' => 'string'),
                            'mime_type' => array('type' => 'string'),
                            'limit' => array('type' => 'integer', 'minimum' => 1, 'maximum' => 20)
                        )
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'list_terms',
                    'description' => 'Search taxonomy terms',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'taxonomy' => array('type' => 'string'),
                            'search' => array('type' => 'string'),
                            'limit' => array('type' => 'integer', 'minimum' => 1, 'maximum' => 50)
                        ),
                        'required' => array('taxonomy')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'restore_post_revision',
                    'description' => 'Restore revision',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'post_id' => array('type' => 'integer'),
                            'revision_id' => array('type' => 'integer')
                        ),
                        'required' => array('post_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'delete_post',
                    'description' => 'Delete post',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'post_id' => array('type' => 'integer'),
                            'confirm' => array('type' => 'boolean')
                        ),
                        'required' => array('post_id', 'confirm')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'upload_media',
                    'description' => 'Upload media',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'url' => array('type' => 'string'),
                            'title' => array('type' => 'string'),
                            'alt_text' => array('type' => 'string'),
                            'caption' => array('type' => 'string'),
                            'description' => array('type' => 'string'),
                            'filename' => array('type' => 'string')
                        ),
                        'required' => array('url')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'update_media_metadata',
                    'description' => 'Update media meta',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'attachment_id' => array('type' => 'integer'),
                            'title' => array('type' => 'string'),
                            'caption' => array('type' => 'string'),
                            'description' => array('type' => 'string'),
                            'alt_text' => array('type' => 'string')
                        ),
                        'required' => array('attachment_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'set_featured_image',
                    'description' => 'Set featured image',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'post_id' => array('type' => 'integer'),
                            'attachment_id' => array('type' => 'integer')
                        ),
                        'required' => array('post_id', 'attachment_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'create_user',
                    'description' => 'Create user',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'username' => array('type' => 'string'),
                            'email' => array('type' => 'string'),
                            'role' => array('type' => 'string'),
                            'first_name' => array('type' => 'string'),
                            'last_name' => array('type' => 'string'),
                            'display_name' => array('type' => 'string'),
                            'password' => array('type' => 'string')
                        ),
                        'required' => array('username', 'email')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'update_user',
                    'description' => 'Update user',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'user_id' => array('type' => 'integer'),
                            'email' => array('type' => 'string'),
                            'first_name' => array('type' => 'string'),
                            'last_name' => array('type' => 'string'),
                            'display_name' => array('type' => 'string'),
                            'password' => array('type' => 'string')
                        ),
                        'required' => array('user_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'change_user_role',
                    'description' => 'Change user role',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'user_id' => array('type' => 'integer'),
                            'role' => array('type' => 'string')
                        ),
                        'required' => array('user_id', 'role')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'delete_user',
                    'description' => 'Delete user',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'user_id' => array('type' => 'integer'),
                            'reassign_to' => array('type' => 'integer'),
                            'confirm' => array('type' => 'boolean')
                        ),
                        'required' => array('user_id', 'confirm')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'update_site_settings',
                    'description' => 'Update site settings',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'site_title' => array('type' => 'string'),
                            'tagline' => array('type' => 'string'),
                            'timezone' => array('type' => 'string'),
                            'date_format' => array('type' => 'string'),
                            'time_format' => array('type' => 'string')
                        )
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'update_discussion_settings',
                    'description' => 'Update discussion settings',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'require_account' => array('type' => 'boolean'),
                            'auto_close_days' => array('type' => 'integer'),
                            'hold_moderation_keywords' => array('type' => 'string'),
                            'comment_moderation' => array('type' => 'boolean'),
                            'comment_max_links' => array('type' => 'integer')
                        )
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'create_term',
                    'description' => 'Create taxonomy term',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'taxonomy' => array('type' => 'string'),
                            'name' => array('type' => 'string'),
                            'slug' => array('type' => 'string'),
                            'description' => array('type' => 'string'),
                            'parent' => array('type' => 'integer')
                        ),
                        'required' => array('name')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'update_term',
                    'description' => 'Update taxonomy term',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'term_id' => array('type' => 'integer'),
                            'taxonomy' => array('type' => 'string'),
                            'name' => array('type' => 'string'),
                            'slug' => array('type' => 'string'),
                            'description' => array('type' => 'string'),
                            'parent' => array('type' => 'integer')
                        ),
                        'required' => array('term_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'delete_term',
                    'description' => 'Delete taxonomy term',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'term_id' => array('type' => 'integer'),
                            'taxonomy' => array('type' => 'string'),
                            'confirm' => array('type' => 'boolean')
                        ),
                        'required' => array('term_id', 'taxonomy', 'confirm')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'assign_terms_to_post',
                    'description' => 'Assign terms to post',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'post_id' => array('type' => 'integer'),
                            'taxonomy' => array('type' => 'string'),
                            'term_ids' => array('type' => 'array', 'items' => array('type' => 'integer')),
                            'append' => array('type' => 'boolean')
                        ),
                        'required' => array('post_id', 'term_ids')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'approve_comment',
                    'description' => 'Approve comment',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'comment_id' => array('type' => 'integer')
                        ),
                        'required' => array('comment_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'trash_comment',
                    'description' => 'Trash comment',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'comment_id' => array('type' => 'integer'),
                            'confirm' => array('type' => 'boolean')
                        ),
                        'required' => array('comment_id', 'confirm')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'reply_to_comment',
                    'description' => 'Reply to comment',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'comment_id' => array('type' => 'integer'),
                            'content' => array('type' => 'string')
                        ),
                        'required' => array('comment_id', 'content')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'create_widget',
                    'description' => 'Create widget',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'id_base' => array('type' => 'string'),
                            'settings' => array('type' => 'object'),
                            'sidebar_id' => array('type' => 'string'),
                            'position' => array('type' => 'integer')
                        ),
                        'required' => array('id_base')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'update_widget',
                    'description' => 'Update widget',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'widget_id' => array('type' => 'string'),
                            'settings' => array('type' => 'object')
                        ),
                        'required' => array('widget_id', 'settings')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'delete_widget',
                    'description' => 'Delete widget',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'widget_id' => array('type' => 'string'),
                            'confirm' => array('type' => 'boolean')
                        ),
                        'required' => array('widget_id', 'confirm')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'assign_widget_to_sidebar',
                    'description' => 'Assign widget',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'widget_id' => array('type' => 'string'),
                            'sidebar_id' => array('type' => 'string'),
                            'position' => array('type' => 'integer')
                        ),
                        'required' => array('widget_id', 'sidebar_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'create_menu',
                    'description' => 'Create menu',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'name' => array('type' => 'string'),
                            'slug' => array('type' => 'string'),
                            'description' => array('type' => 'string')
                        ),
                        'required' => array('name')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'update_menu',
                    'description' => 'Update menu',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'menu_id' => array('type' => 'integer'),
                            'name' => array('type' => 'string'),
                            'slug' => array('type' => 'string'),
                            'description' => array('type' => 'string')
                        ),
                        'required' => array('menu_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'delete_menu',
                    'description' => 'Delete menu',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'menu_id' => array('type' => 'integer'),
                            'confirm' => array('type' => 'boolean')
                        ),
                        'required' => array('menu_id', 'confirm')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'assign_menu_location',
                    'description' => 'Assign menu location',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'menu_id' => array('type' => 'integer'),
                            'location' => array('type' => 'string')
                        ),
                        'required' => array('menu_id', 'location')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'add_menu_item',
                    'description' => 'Add menu item',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'menu_id' => array('type' => 'integer'),
                            'title' => array('type' => 'string'),
                            'url' => array('type' => 'string'),
                            'parent_id' => array('type' => 'integer'),
                            'position' => array('type' => 'integer')
                        ),
                        'required' => array('menu_id', 'title')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'update_menu_item',
                    'description' => 'Update menu item',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'menu_id' => array('type' => 'integer'),
                            'item_id' => array('type' => 'integer'),
                            'title' => array('type' => 'string'),
                            'url' => array('type' => 'string'),
                            'parent_id' => array('type' => 'integer'),
                            'position' => array('type' => 'integer')
                        ),
                        'required' => array('menu_id', 'item_id')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'delete_menu_item',
                    'description' => 'Delete menu item',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'menu_id' => array('type' => 'integer'),
                            'item_id' => array('type' => 'integer'),
                            'confirm' => array('type' => 'boolean')
                        ),
                        'required' => array('menu_id', 'item_id', 'confirm')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'activate_plugin',
                    'description' => 'Activate plugin',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'plugin' => array('type' => 'string'),
                            'network_wide' => array('type' => 'boolean')
                        ),
                        'required' => array('plugin')
                    )
                )
            ),
            array(
                'type' => 'function',
                'function' => array(
                    'name' => 'deactivate_plugin',
                    'description' => 'Deactivate plugin',
                    'parameters' => array(
                        'type' => 'object',
                        'properties' => array(
                            'plugin' => array('type' => 'string'),
                            'network_wide' => array('type' => 'boolean'),
                            'confirm' => array('type' => 'boolean')
                        ),
                        'required' => array('plugin', 'confirm')
                    )
                )
            )
        );

        return apply_filters('nietos_ai_tools', $tools);
    }

    /**
     * Get mapped tool definitions keyed by function name.
     */
    private function get_tool_definitions() {
        static $definitions = null;

        if ($definitions === null) {
            $definitions = array();
            foreach ($this->build_all_tools() as $tool) {
                if (isset($tool['function']['name'])) {
                    $definitions[$tool['function']['name']] = $tool;
                }
            }
        }

        return $definitions;
    }

    /**
     * Determine which tool groups to expose based on the latest user intent.
     */
    private function determine_tool_groups($messages) {
        $groups = array();
        $combined_text = '';

        if (is_array($messages)) {
            $collected = 0;
            for ($i = count($messages) - 1; $i >= 0; $i--) {
                $message = $messages[$i];
                if (!isset($message['role']) || $message['role'] !== 'user') {
                    continue;
                }

                if (empty($message['content']) || !is_string($message['content'])) {
                    continue;
                }

                $combined_text .= ' ' . strtolower($message['content']);
                $collected++;

                if ($collected >= 3) {
                    break;
                }
            }
        }

        $combined_text = trim($combined_text);

        if ($combined_text === '') {
            return array('core');
        }

        $text = $combined_text;

        if ($this->string_contains_any($text, array('post', 'page', 'content', 'article', 'edit', 'update', 'modify', 'change', 'create', 'new', 'draft', 'publish', 'revision', 'translate', 'list'))) {
            $groups[] = 'core';
        }

        if ($this->string_contains_any($text, array('image', 'media', 'photo', 'picture', 'gallery', 'alt text', 'thumbnail', 'featured'))) {
            $groups[] = 'media';
        }

        if ($this->string_contains_any($text, array('category', 'tag', 'taxonomy', 'term'))) {
            $groups[] = 'taxonomy';
        }

        if ($this->string_contains_any($text, array('comment', 'moderate', 'reply'))) {
            $groups[] = 'comments';
        }

        if ($this->string_contains_any($text, array('user', 'role', 'account', 'profile', 'password'))) {
            $groups[] = 'users';
        }

        if ($this->string_contains_any($text, array('widget', 'sidebar'))) {
            $groups[] = 'widgets';
        }

        if ($this->string_contains_any($text, array('menu', 'navigation'))) {
            $groups[] = 'menus';
        }

        if ($this->string_contains_any($text, array('plugin', 'extension'))) {
            $groups[] = 'plugins';
        }

        if ($this->string_contains_any($text, array('setting', 'timezone', 'title', 'tagline', 'permalink', 'discussion'))) {
            $groups[] = 'settings';
        }

        if (empty($groups)) {
            $groups[] = 'core';
        }

        return array_values(array_unique($groups));
    }

    /**
     * Map of tool groups to tool names.
     */
    private function get_tool_groups() {
        return array(
            'core' => array('create_post', 'update_post', 'get_post_content', 'get_post_blocks', 'update_post_blocks', 'list_block_patterns', 'apply_block_pattern', 'find_posts', 'list_post_revisions', 'restore_post_revision', 'delete_post'),
            'media' => array('find_media', 'upload_media', 'update_media_metadata', 'set_featured_image'),
            'taxonomy' => array('list_terms', 'create_term', 'update_term', 'delete_term', 'assign_terms_to_post'),
            'comments' => array('approve_comment', 'trash_comment', 'reply_to_comment'),
            'users' => array('create_user', 'update_user', 'change_user_role', 'delete_user'),
            'widgets' => array('create_widget', 'update_widget', 'delete_widget', 'assign_widget_to_sidebar'),
            'menus' => array('create_menu', 'update_menu', 'delete_menu', 'assign_menu_location', 'add_menu_item', 'update_menu_item', 'delete_menu_item'),
            'plugins' => array('activate_plugin', 'deactivate_plugin'),
            'settings' => array('update_site_settings', 'update_discussion_settings')
        );
    }

    /**
     * Get default tool names used when no specific intent is detected.
     */
    private function get_default_tool_names() {
        return $this->get_tool_groups()['core'];
    }

    /**
     * Select tools relevant to the user intent to keep the OpenAI schema compact.
     */
    private function get_wordpress_tools($messages = array(), $tool_groups = null) {
        $definitions = $this->get_tool_definitions();
        $groups = is_array($tool_groups) ? $tool_groups : $this->determine_tool_groups($messages);
        $group_map = $this->get_tool_groups();

        $tool_names = array();
        foreach ($groups as $group) {
            if (isset($group_map[$group])) {
                $tool_names = array_merge($tool_names, $group_map[$group]);
            }
        }

        if (empty($tool_names)) {
            $tool_names = $this->get_default_tool_names();
        }

        $tool_names = array_values(array_unique($tool_names));

        $selected_tools = array();
        foreach ($tool_names as $name) {
            if (isset($definitions[$name])) {
                $selected_tools[] = $definitions[$name];
            }
        }

        return apply_filters('nietos_ai_selected_tools', $selected_tools, $tool_names, $messages);
    }

    /**
     * Render an array of GPT-provided block definitions into Gutenberg markup
     */
    private function render_blocks_collection($blocks) {
        if (empty($blocks) || !is_array($blocks)) {
            return new WP_Error('invalid_blocks_payload', __('Blocks payload must be a non-empty array.', 'nietos-ai'));
        }

        $output = '';

        foreach ($blocks as $index => $block_def) {
            if (!is_array($block_def)) {
                return new WP_Error('invalid_block_definition', sprintf(
                    /* translators: %d: block index number */
                    __('Block definition at index %d must be an object.', 'nietos-ai'),
                    $index
                ));
            }

            $rendered = $this->render_single_block($block_def);

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

            $output .= trim($rendered) . "\n\n";
        }

        return trim($output);
    }

    /**
     * Render a single block definition
     */
    private function render_single_block($block_def) {
        $block_name = $this->normalize_block_name($block_def['type'] ?? 'paragraph');
        $attrs = isset($block_def['attrs']) && is_array($block_def['attrs']) ? $block_def['attrs'] : array();
        $content = isset($block_def['content']) ? $block_def['content'] : '';
        $inner_blocks = isset($block_def['inner_blocks']) && is_array($block_def['inner_blocks']) ? $block_def['inner_blocks'] : array();

        $inner_markup = '';
        if (!empty($inner_blocks)) {
            $rendered = $this->render_blocks_collection($inner_blocks);
            if (is_wp_error($rendered)) {
                return $rendered;
            }
            $inner_markup = $rendered;
        }

        $html = '';
        $block_type = $this->normalize_block_type($block_name);

        switch ($block_type) {
            case 'heading':
                $level = isset($attrs['level']) ? (int) $attrs['level'] : 2;
                if ($level < 1 || $level > 6) {
                    $level = 2;
                }
                $html = sprintf('<h%d>%s</h%d>', $level, wp_kses_post($content), $level);
                break;

            case 'paragraph':
                $html = '<p>' . wp_kses_post($content) . '</p>';
                break;

            case 'list':
                $items = array();
                if (isset($block_def['items']) && is_array($block_def['items'])) {
                    $items = $block_def['items'];
                } elseif (!empty($content)) {
                    $items = array_map('trim', explode("\n", (string) $content));
                }
                $items = array_filter($items, function ($item) {
                    return $item !== '';
                });
                $tag = (!empty($attrs['ordered'])) ? 'ol' : 'ul';
                $html .= '<' . $tag . '>';
                foreach ($items as $item) {
                    $html .= '<li>' . wp_kses_post($item) . '</li>';
                }
                $html .= '</' . $tag . '>';
                break;

            case 'quote':
                $citation = isset($block_def['citation']) ? wp_kses_post($block_def['citation']) : '';
                $html = '<blockquote>' . wpautop(wp_kses_post($content));
                if ($citation !== '') {
                    $html .= '<cite>' . $citation . '</cite>';
                }
                $html .= '</blockquote>';
                break;

            case 'image':
                $url = isset($attrs['url']) ? esc_url_raw($attrs['url']) : '';
                if ($url === '') {
                    return new WP_Error('invalid_image_block', __('Image blocks require a URL.', 'nietos-ai'));
                }
                $alt = isset($attrs['alt']) ? esc_attr($attrs['alt']) : '';
                $html = '<figure class="wp-block-image">';
                $html .= '<img src="' . $url . '" alt="' . $alt . '" />';
                if (!empty($content)) {
                    $html .= '<figcaption>' . wp_kses_post($content) . '</figcaption>';
                }
                $html .= '</figure>';
                break;

            case 'columns':
            case 'group':
            case 'column':
                $wrapper_tag = $block_type === 'group' ? 'div' : 'div';
                $class = 'wp-block-' . $block_type;
                $inner = $inner_markup;
                if ($inner === '') {
                    $inner = wpautop(wp_kses_post($content));
                }
                $html = '<' . $wrapper_tag . ' class="' . esc_attr($class) . '">' . $inner . '</' . $wrapper_tag . '>';
                break;

            default:
                $inner = $inner_markup;
                if ($inner === '') {
                    $inner = wpautop(wp_kses_post($content));
                }
                $html = $inner;
                break;
        }

        $markup = $this->wrap_block_markup($block_name, $attrs, $html);

        if ($inner_markup !== '' && in_array($block_type, array('group', 'columns', 'column'), true)) {
            // wrap_block_markup already contains $html, which for these types included $inner_markup
            return $markup;
        }

        if ($inner_markup !== '' && $block_type !== 'group' && $block_type !== 'columns' && $block_type !== 'column') {
            // Append nested blocks inside main HTML for blocks that accept inner blocks
            $combined_html = $html . "\n" . $inner_markup;
            $markup = $this->wrap_block_markup($block_name, $attrs, $combined_html);
        }

        return $markup;
    }

    /**
     * Normalize incoming block type to full block name (e.g. paragraph -> core/paragraph)
     */
    private function normalize_block_name($type) {
        $name = strtolower(trim((string) $type));

        if ($name === '') {
            $name = 'paragraph';
        }

        // Already namespaced
        if (strpos($name, '/') !== false) {
            return $name;
        }

        switch ($name) {
            case 'p':
            case 'para':
            case 'paragraph':
                return 'core/paragraph';
            case 'h1':
            case 'h2':
            case 'h3':
            case 'h4':
            case 'h5':
            case 'h6':
            case 'heading':
                return 'core/heading';
            case 'list':
            case 'ul':
            case 'ol':
                return 'core/list';
            case 'quote':
            case 'blockquote':
                return 'core/quote';
            case 'image':
            case 'img':
                return 'core/image';
            case 'columns':
                return 'core/columns';
            case 'column':
                return 'core/column';
            case 'group':
                return 'core/group';
            case 'separator':
                return 'core/separator';
            default:
                return 'core/' . $name;
        }
    }

    /**
     * Wrap raw HTML inside Gutenberg comment delimiters
     */
    private function wrap_block_markup($block_name, $attrs, $inner_html) {
        $attrs_json = '';
        if (!empty($attrs)) {
            $attrs_json = ' ' . wp_json_encode($attrs);
        }

        $open = sprintf('<!-- wp:%s%s -->', $block_name, $attrs_json);
        $close = sprintf('<!-- /wp:%s -->', $block_name);

        return $open . "\n" . trim($inner_html) . "\n" . $close;
    }

    /**
     * Normalize block name to simple type
     */
    private function normalize_block_type($block_name) {
        if (strpos((string) $block_name, '/') !== false) {
            list(, $name) = explode('/', $block_name, 2);
            return $name;
        }

        return (string) $block_name;
    }

    /**
     * Extract the latest user instruction snippet
     */
    private function get_latest_user_instruction($messages) {
        if (empty($messages) || !is_array($messages)) {
            return '';
        }

        for ($i = count($messages) - 1; $i >= 0; $i--) {
            $message = $messages[$i];
            if (isset($message['role']) && $message['role'] === 'user' && !empty($message['content'])) {
                $content = wp_strip_all_tags((string) $message['content']);
                $content = trim(preg_replace('/\s+/', ' ', $content));
                if ($content !== '') {
                    if (strlen($content) > 280) {
                        $content = mb_substr($content, 0, 280) . '…';
                    }
                    return $content;
                }
            }
        }

        return '';
    }

    /**
     * Helper to see if any of the needles exist in the haystack string.
     */
    private function string_contains_any($haystack, $needles) {
        foreach ($needles as $needle) {
            if (strpos($haystack, $needle) !== false) {
                return true;
            }
        }

        return false;
    }

    /**
     * Execute WordPress operation
     */
    private function execute_operation($operation, $args) {
        switch ($operation) {
            case 'create_post':
                return $this->create_post($args);

            case 'update_post':
                return $this->update_post($args);

            case 'get_post_content':
                return $this->get_post_content($args);

            case 'get_post_blocks':
                return $this->get_post_blocks($args);

            case 'find_posts':
                return $this->find_posts($args);

            case 'find_media':
                return $this->find_media($args);

            case 'list_terms':
                return $this->list_terms($args);

            case 'list_block_patterns':
                return $this->list_block_patterns($args);

            case 'list_post_revisions':
                return $this->list_post_revisions($args);

            case 'restore_post_revision':
                return $this->restore_post_revision($args);

            case 'update_post_blocks':
                return $this->update_post_blocks($args);

            case 'apply_block_pattern':
                return $this->apply_block_pattern($args);

            case 'delete_post':
                return $this->delete_post($args);

            case 'upload_media':
                return $this->upload_media($args);

            case 'update_media_metadata':
                return $this->update_media_metadata($args);

            case 'set_featured_image':
                return $this->set_featured_image($args);

            case 'create_user':
                return $this->create_user($args);

            case 'update_user':
                return $this->update_user($args);

            case 'change_user_role':
                return $this->change_user_role($args);

            case 'delete_user':
                return $this->delete_user($args);

            case 'update_site_settings':
                return $this->update_site_settings($args);

            case 'update_discussion_settings':
                return $this->update_discussion_settings($args);

            case 'create_term':
                return $this->create_term($args);

            case 'update_term':
                return $this->update_term($args);

            case 'delete_term':
                return $this->delete_term($args);

            case 'assign_terms_to_post':
                return $this->assign_terms_to_post($args);

            case 'approve_comment':
                return $this->approve_comment($args);

            case 'trash_comment':
                return $this->trash_comment($args);

            case 'reply_to_comment':
                return $this->reply_to_comment($args);

            case 'create_widget':
                return $this->create_widget($args);

            case 'update_widget':
                return $this->update_widget($args);

            case 'delete_widget':
                return $this->delete_widget($args);

            case 'assign_widget_to_sidebar':
                return $this->assign_widget_to_sidebar($args);

            case 'create_menu':
                return $this->create_menu($args);

            case 'update_menu':
                return $this->update_menu($args);

            case 'delete_menu':
                return $this->delete_menu($args);

            case 'assign_menu_location':
                return $this->assign_menu_location($args);

            case 'add_menu_item':
                return $this->add_menu_item($args);

            case 'update_menu_item':
                return $this->update_menu_item($args);

            case 'delete_menu_item':
                return $this->delete_menu_item($args);

            case 'activate_plugin':
                return $this->activate_plugin($args);

            case 'deactivate_plugin':
                return $this->deactivate_plugin($args);

            default:
                return new WP_Error('invalid_operation', __('Invalid operation', 'nietos-ai'));
        }
    }

    /**
     * Create post
     */
    private function create_post($args) {
        $post_type = isset($args['post_type']) ? sanitize_key($args['post_type']) : 'post';
        if ($post_type === '') {
            $post_type = 'post';
        }

        if (!post_type_exists($post_type)) {
            return new WP_Error('invalid_post_type', __('The specified post type does not exist.', 'nietos-ai'));
        }

        $post_type_object = get_post_type_object($post_type);
        $required_capability = 'edit_posts';

        if ($post_type_object && !empty($post_type_object->cap->create_posts)) {
            $required_capability = $post_type_object->cap->create_posts;
        }

        if (!current_user_can($required_capability)) {
            return new WP_Error('forbidden', __('You do not have permission to create this type of content.', 'nietos-ai'), array('status' => 403));
        }

        $status = isset($args['status']) ? sanitize_key($args['status']) : 'draft';
        $allowed_statuses = get_post_stati(array('internal' => false));
        if (!in_array($status, $allowed_statuses, true)) {
            $status = 'draft';
        }

        $post_data = array(
            'post_title' => isset($args['title']) ? wp_strip_all_tags($args['title']) : '',
            'post_content' => $args['content'] ?? '',
            'post_type' => $post_type,
            'post_status' => $status,
            'post_author' => get_current_user_id()
        );

        $post_id = wp_insert_post($post_data, true);

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

        return array(
            'success' => true,
            'post_id' => $post_id,
            'edit_url' => get_edit_post_link($post_id, 'raw')
        );
    }

    /**
     * Update post
     */
    private function update_post($args) {
        $post_id = isset($args['post_id']) ? absint($args['post_id']) : 0;

        if (!$post_id) {
            return new WP_Error('no_post_id', __('Post ID is required', 'nietos-ai'));
        }

        if (!current_user_can('edit_post', $post_id)) {
            return new WP_Error('forbidden', __('You do not have permission to edit this post.', 'nietos-ai'), array('status' => 403));
        }

        $post = get_post($post_id);
        if (!$post) {
            return new WP_Error('post_not_found', __('The requested post could not be found.', 'nietos-ai'));
        }

        $post_data = array(
            'ID' => $post_id
        );

        if (isset($args['title'])) {
            $post_data['post_title'] = $args['title'];
        }

        if (isset($args['content'])) {
            $post_data['post_content'] = $args['content'];
        }

        if (isset($args['status'])) {
            $status = sanitize_key($args['status']);
            $allowed_statuses = get_post_stati(array('internal' => false));
            if (!in_array($status, $allowed_statuses, true)) {
                $status = $post->post_status;
            }
            $post_data['post_status'] = $status;
        }

        $result = wp_update_post($post_data, true);

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

        return array(
            'success' => true,
            'post_id' => $post_id
        );
    }

    /**
     * Get the latest content and metadata for a post
     */
    private function get_post_content($args) {
        $post_id = isset($args['post_id']) ? absint($args['post_id']) : 0;

        if (!$post_id || $post_id < 1) {
            return new WP_Error('invalid_post_id', __('Valid Post ID is required', 'nietos-ai'));
        }

        if (!current_user_can('edit_post', $post_id)) {
            return new WP_Error('forbidden', __('You do not have permission to view this post.', 'nietos-ai'), array('status' => 403));
        }

        $post = get_post($post_id);

        if (!$post) {
            return new WP_Error('post_not_found', __('The requested post could not be found.', 'nietos-ai'));
        }

        $blocks_summary = array();
        if (function_exists('parse_blocks')) {
            $parsed_blocks = parse_blocks($post->post_content);

            foreach ($parsed_blocks as $block) {
                $blocks_summary[] = array(
                    'name' => isset($block['blockName']) ? $block['blockName'] : 'core/undefined',
                    'summary' => isset($block['innerHTML']) ? wp_trim_words(wp_strip_all_tags($block['innerHTML']), 20, '…') : ''
                );
            }
        }

        return array(
            'success' => true,
            'post' => array(
                'post_id' => $post->ID,
                'title' => get_the_title($post),
                'content' => $post->post_content,
                'excerpt' => $post->post_excerpt,
                'post_type' => $post->post_type,
                'status' => $post->post_status,
                'author_id' => (int) $post->post_author,
                'author_name' => get_the_author_meta('display_name', $post->post_author),
                'date' => mysql2date('c', $post->post_date),
                'modified' => mysql2date('c', $post->post_modified),
                'edit_url' => get_edit_post_link($post->ID, 'raw'),
                'permalink' => get_permalink($post->ID),
                'blocks' => $blocks_summary
            )
        );
    }

    /**
     * Get Gutenberg block summary for a post
     */
    private function get_post_blocks($args) {
        $post_id = isset($args['post_id']) ? absint($args['post_id']) : 0;
        $include_html = !empty($args['include_html']);

        if (!$post_id) {
            return new WP_Error('no_post_id', __('Post ID is required', 'nietos-ai'));
        }

        if (!current_user_can('edit_post', $post_id)) {
            return new WP_Error('forbidden', __('You do not have permission to view this post.', 'nietos-ai'), array('status' => 403));
        }

        $post = get_post($post_id);

        if (!$post) {
            return new WP_Error('post_not_found', __('The requested post could not be found.', 'nietos-ai'));
        }

        $parsed_blocks = function_exists('parse_blocks') ? parse_blocks($post->post_content) : array();
        $results = array();
        $index = 0;

        foreach ($parsed_blocks as $block) {
            $block_name = isset($block['blockName']) && $block['blockName'] ? $block['blockName'] : 'core/paragraph';
            $summary_source = '';

            if (!empty($block['innerHTML'])) {
                $summary_source = $block['innerHTML'];
            } elseif (function_exists('render_block')) {
                $summary_source = render_block($block);
            }

            $entry = array(
                'index' => $index,
                'block_name' => $block_name,
                'type' => $this->normalize_block_type($block_name),
                'has_inner_blocks' => !empty($block['innerBlocks']),
                'summary' => wp_trim_words(wp_strip_all_tags($summary_source), 40, '…')
            );

            if (!empty($block['attrs'])) {
                $entry['attrs'] = $block['attrs'];
            }

            if ($include_html && !empty($summary_source)) {
                $entry['inner_html'] = trim($summary_source);
            }

            $results[] = $entry;
            $index++;
        }

        return array(
            'success' => true,
            'post_id' => $post_id,
            'total_blocks' => count($results),
            'blocks' => $results
        );
    }

    /**
     * Find posts or pages matching a search query
     */
    private function find_posts($args) {
        if (!current_user_can('edit_posts')) {
            return new WP_Error('forbidden', __('You do not have permission to search posts.', 'nietos-ai'), array('status' => 403));
        }

        $search = isset($args['search']) ? sanitize_text_field(wp_unslash($args['search'])) : '';

        $post_types = array('post', 'page');
        if (isset($args['post_type'])) {
            $raw_types = is_array($args['post_type']) ? $args['post_type'] : explode(',', (string) $args['post_type']);
            $post_types = array();

            foreach ($raw_types as $type) {
                $type = sanitize_key(trim((string) $type));
                if (!empty($type)) {
                    $post_types[] = $type;
                }
            }

            if (empty($post_types)) {
                $post_types = array('post', 'page');
            }
        }

        $statuses = array('publish', 'draft', 'pending', 'future', 'private');
        if (isset($args['status'])) {
            $raw_statuses = is_array($args['status']) ? $args['status'] : explode(',', (string) $args['status']);
            $statuses = array();

            foreach ($raw_statuses as $status) {
                $status = sanitize_key(trim((string) $status));
                if (!empty($status)) {
                    $statuses[] = $status;
                }
            }

            if (empty($statuses)) {
                $statuses = array('publish', 'draft', 'pending', 'future', 'private');
            }
        }

        $limit = isset($args['limit']) ? absint($args['limit']) : 10;
        if ($limit < 1) {
            $limit = 1;
        }
        if ($limit > 20) {
            $limit = 20;
        }

        $query_args = array(
            'post_type' => $post_types,
            'post_status' => $statuses,
            'posts_per_page' => $limit,
            'orderby' => 'date',
            'order' => 'DESC'
        );

        if ($search !== '') {
            $query_args['s'] = $search;
        }

        $results = array();
        $seen_ids = array();

        $search_lower = strtolower($search);
        if (
            $search_lower !== ''
            && $this->string_contains_any(
                $search_lower,
                array('homepage', 'home page', 'front page', 'etusivu')
            )
        ) {
            $front_page_id = (int) get_option('page_on_front');
            if ($front_page_id) {
                $front_page = get_post($front_page_id);
                if ($front_page && current_user_can('edit_post', $front_page_id)) {
                    $results[] = array(
                        'post_id' => $front_page->ID,
                        'title' => get_the_title($front_page->ID),
                        'post_type' => $front_page->post_type,
                        'status' => get_post_status($front_page->ID),
                        'date' => mysql2date('c', $front_page->post_date),
                        'modified' => mysql2date('c', $front_page->post_modified),
                        'edit_url' => get_edit_post_link($front_page->ID, 'raw'),
                        'permalink' => get_permalink($front_page->ID)
                    );
                    $seen_ids[$front_page->ID] = true;
                }
            }
        }

        $posts = get_posts($query_args);

        foreach ($posts as $post) {
            if (!current_user_can('edit_post', $post->ID)) {
                continue;
            }

            if (isset($seen_ids[$post->ID])) {
                continue;
            }

            $results[] = array(
                'post_id' => $post->ID,
                'title' => get_the_title($post->ID),
                'post_type' => $post->post_type,
                'status' => get_post_status($post->ID),
                'date' => mysql2date('c', $post->post_date),
                'modified' => mysql2date('c', $post->post_modified),
                'edit_url' => get_edit_post_link($post->ID, 'raw'),
                'permalink' => get_permalink($post->ID)
            );
        }

        return array(
            'success' => true,
            'search' => $search,
            'results' => $results,
            'total_found' => count($results)
        );
    }

    /**
     * Update Gutenberg blocks for a post
     */
    private function update_post_blocks($args) {
        $post_id = isset($args['post_id']) ? absint($args['post_id']) : 0;
        $mode = isset($args['mode']) ? strtolower(sanitize_text_field($args['mode'])) : 'replace';
        $allowed_modes = array('replace', 'append', 'prepend');

        if (!in_array($mode, $allowed_modes, true)) {
            $mode = 'replace';
        }

        if (!$post_id) {
            return new WP_Error('no_post_id', __('Post ID is required', 'nietos-ai'));
        }

        if (!current_user_can('edit_post', $post_id)) {
            return new WP_Error('forbidden', __('You do not have permission to edit this post.', 'nietos-ai'), array('status' => 403));
        }

        $post = get_post($post_id);

        if (!$post) {
            return new WP_Error('post_not_found', __('The requested post could not be found.', 'nietos-ai'));
        }

        $content = '';

        if (!empty($args['gutenberg_content'])) {
            $raw_content = $args['gutenberg_content'];
            if (is_array($raw_content)) {
                $raw_content = implode("\n\n", $raw_content);
            }
            $content = trim((string) $raw_content);
        }

        if (empty($content) && !empty($args['blocks']) && is_array($args['blocks'])) {
            $rendered = $this->render_blocks_collection($args['blocks']);
            if (is_wp_error($rendered)) {
                return $rendered;
            }
            $content = $rendered;
        }

        if ($content === '') {
            return new WP_Error('no_content', __('Gutenberg content is required', 'nietos-ai'));
        }

        if (function_exists('parse_blocks')) {
            $parsed = parse_blocks($content);
            if (empty($parsed) && strpos($content, '<!-- wp:') === false) {
                return new WP_Error('invalid_blocks', __('Provided content does not contain valid Gutenberg blocks.', 'nietos-ai'));
            }
        }

        $existing_content = (string) $post->post_content;

        $preserve_structure = true;
        if (isset($args['preserve_structure'])) {
            $preserve_structure = (bool) $args['preserve_structure'];
        }

        if (
            $mode === 'replace'
            && $preserve_structure
            && function_exists('parse_blocks')
            && function_exists('serialize_blocks')
        ) {
            $merged_content = $this->merge_text_into_existing_blocks($existing_content, $content);
            if (is_wp_error($merged_content)) {
                return $merged_content;
            }
            if (is_string($merged_content) && $merged_content !== '') {
                $content = $merged_content;
            }
        }

        if ($mode === 'append') {
            $content = rtrim($existing_content) . "\n\n" . $content;
        } elseif ($mode === 'prepend') {
            $content = $content . "\n\n" . ltrim($existing_content);
        }

        $result = wp_update_post(array(
            'ID' => $post_id,
            'post_content' => wp_slash($content)
        ), true);

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

        return array(
            'success' => true,
            'post_id' => $post_id,
            'mode' => $mode,
            'message' => __('Post content updated with provided Gutenberg blocks.', 'nietos-ai')
        );
    }

    /**
     * Attempt to merge new textual content into the existing block structure.
     */
    private function merge_text_into_existing_blocks($existing_content, $new_content) {
        $existing_blocks = parse_blocks($existing_content);
        $new_blocks = parse_blocks($new_content);

        if (empty($existing_blocks) || empty($new_blocks)) {
            return '';
        }

        $text_queue = $this->extract_text_from_blocks($new_blocks);
        if (empty($text_queue)) {
            return '';
        }

        $updated_blocks = $existing_blocks;
        $replaced_count = $this->apply_text_updates_to_blocks($updated_blocks, $text_queue);

        if ($replaced_count === 0) {
            return '';
        }

        return serialize_blocks($updated_blocks);
    }

    /**
     * Extract plain text snippets from blocks in document order.
     */
    private function extract_text_from_blocks($blocks) {
        $texts = array();

        foreach ($blocks as $block) {
            $texts = array_merge($texts, $this->extract_text_from_block_recursive($block));
        }

        return array_values(array_filter(array_map('trim', $texts), static function ($text) {
            return $text !== '';
        }));
    }

    /**
     * Recursively extract text from a single block.
     */
    private function extract_text_from_block_recursive($block) {
        $texts = array();
        $block_name = isset($block['blockName']) ? $block['blockName'] : '';

        if ($this->is_textual_block($block_name)) {
            $raw = '';
            if (!empty($block['innerContent'])) {
                $raw = implode('', $block['innerContent']);
            } elseif (isset($block['innerHTML'])) {
                $raw = $block['innerHTML'];
            }
            if ($raw !== '') {
                $texts[] = wp_strip_all_tags($raw);
            }
        }

        if (!empty($block['innerBlocks'])) {
            foreach ($block['innerBlocks'] as $inner) {
                $texts = array_merge($texts, $this->extract_text_from_block_recursive($inner));
            }
        }

        return $texts;
    }

    /**
     * Apply queued text snippets onto the existing block tree.
     */
    private function apply_text_updates_to_blocks(&$blocks, &$texts) {
        $replaced = 0;

        foreach ($blocks as &$block) {
            $block_name = isset($block['blockName']) ? $block['blockName'] : '';

            if ($this->is_textual_block($block_name) && !empty($texts)) {
                $text = array_shift($texts);
                if ($this->replace_block_text($block, $text)) {
                    $replaced++;
                }
            }

            if (!empty($block['innerBlocks'])) {
                $replaced += $this->apply_text_updates_to_blocks($block['innerBlocks'], $texts);
            }
        }

        return $replaced;
    }

    /**
     * Determine if block represents plain text content we can safely replace.
     */
    private function is_textual_block($block_name) {
        return in_array($block_name, array('core/heading', 'core/paragraph'), true);
    }

    /**
     * Replace block text while keeping structure and attributes.
     */
    private function replace_block_text(&$block, $text) {
        $text = trim((string) $text);

        if ($text === '') {
            return false;
        }

        $block_name = isset($block['blockName']) ? $block['blockName'] : '';
        $safe_text = esc_html($text);

        if ($block_name === 'core/heading') {
            $level = isset($block['attrs']['level']) ? (int) $block['attrs']['level'] : 2;
            if ($level < 1 || $level > 6) {
                $level = 2;
            }

            $existing_html = isset($block['innerHTML']) ? trim($block['innerHTML']) : '';
            $html = '';

            if ($existing_html !== '' && preg_match('/^<(h[1-6])([^>]*)>(.*)<\/\1>$/is', $existing_html, $matches)) {
                $tag = strtolower($matches[1]);
                $attrs = $matches[2];
                $html = '<' . $tag . $attrs . '>' . $safe_text . '</' . $tag . '>';
            } else {
                $html = sprintf('<h%d>%s</h%d>', $level, $safe_text, $level);
            }

            $block['innerHTML'] = $html;
            $block['innerContent'] = array($html);
            $block['attrs']['content'] = $text;
            return true;
        }

        if ($block_name === 'core/paragraph') {
            $existing_html = isset($block['innerHTML']) ? trim($block['innerHTML']) : '';
            $html = '';

            if ($existing_html !== '' && preg_match('/^<p([^>]*)>(.*)<\/p>$/is', $existing_html, $matches)) {
                $attrs = $matches[1];
                $html = '<p' . $attrs . '>' . $safe_text . '</p>';
            } else {
                $html = '<p>' . $safe_text . '</p>';
            }

            $block['innerHTML'] = $html;
            $block['innerContent'] = array($html);
            $block['attrs']['content'] = $text;
            return true;
        }

        return false;
    }

    /**
     * List available Gutenberg block patterns
     */
    private function list_block_patterns($args) {
        $is_debug = defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG;

        if (!current_user_can('edit_posts')) {
            if ($is_debug) {
                error_log('Nietos AI: list_block_patterns - Permission denied');
            }
            return new WP_Error('forbidden', __('You do not have permission to view block patterns.', 'nietos-ai'), array('status' => 403));
        }

        if (!class_exists('WP_Block_Patterns_Registry')) {
            if ($is_debug) {
                error_log('Nietos AI: list_block_patterns - WP_Block_Patterns_Registry not available');
            }
            return new WP_Error('patterns_unavailable', __('Block patterns are not available on this site.', 'nietos-ai'));
        }

        $search = isset($args['search']) ? sanitize_text_field($args['search']) : '';
        $category = isset($args['category']) ? sanitize_key($args['category']) : '';
        $limit = isset($args['limit']) ? absint($args['limit']) : 20;
        if ($limit < 1) {
            $limit = 1;
        }
        if ($limit > 50) {
            $limit = 50;
        }

        $registry = WP_Block_Patterns_Registry::get_instance();
        $patterns = $registry->get_all_registered();

        if ($is_debug) {
            error_log('Nietos AI: list_block_patterns - Found ' . count($patterns) . ' total patterns (search: "' . $search . '", category: "' . $category . '", limit: ' . $limit . ')');
        }

        // Debug: Log first pattern's actual structure
        if ($is_debug && count($patterns) > 0) {
            $first_key = array_key_first($patterns);
            error_log('Nietos AI: First pattern key type: ' . gettype($first_key) . ', value: ' . var_export($first_key, true));
            error_log('Nietos AI: First pattern data: ' . json_encode($patterns[$first_key]));
        }

        $results = array();

        foreach ($patterns as $key => $pattern) {
            $matches = true;

            // IMPORTANT: WordPress returns patterns in a numerically indexed array,
            // but the actual pattern name is stored in $pattern['name']
            $pattern_name = isset($pattern['name']) ? $pattern['name'] : (string) $key;

            if ($search !== '') {
                $haystack = strtolower($pattern['title'] . ' ' . ($pattern['description'] ?? ''));
                if (strpos($haystack, strtolower($search)) === false) {
                    $matches = false;
                }
            }

            if ($matches && $category !== '') {
                $categories = isset($pattern['categories']) ? (array) $pattern['categories'] : array();
                if (!in_array($category, $categories, true)) {
                    $matches = false;
                }
            }

            if (!$matches) {
                continue;
            }

            $results[] = array(
                'name' => $pattern_name,  // Use the pattern's actual name, not the array index
                'title' => $pattern['title'],
                'description' => $pattern['description'] ?? '',
                'categories' => isset($pattern['categories']) ? array_values((array) $pattern['categories']) : array(),
                'keywords' => isset($pattern['keywords']) ? array_values((array) $pattern['keywords']) : array(),
                'viewport_width' => isset($pattern['viewportWidth']) ? (int) $pattern['viewportWidth'] : null,
                'block_types' => isset($pattern['blockTypes']) ? array_values((array) $pattern['blockTypes']) : array()
            );

            if (count($results) >= $limit) {
                break;
            }
        }

        if ($is_debug) {
            error_log('Nietos AI: list_block_patterns - Returning ' . count($results) . ' filtered patterns');
        }

        if ($is_debug && count($results) > 0) {
            // Log first few pattern names for debugging
            $sample_names = array_slice(array_column($results, 'name'), 0, 3);
            error_log('Nietos AI: Sample pattern names returned to AI: ' . implode(', ', $sample_names));

            // Log the full first result for debugging
            error_log('Nietos AI: First pattern full data: ' . json_encode($results[0]));
        }

        return array(
            'success' => true,
            'search' => $search,
            'category' => $category,
            'results' => $results,
            'total_returned' => count($results),
            'total_available' => count($patterns)
        );
    }

    /**
     * Apply a Gutenberg block pattern to a post
     */
    private function apply_block_pattern($args) {
        $post_id = isset($args['post_id']) ? absint($args['post_id']) : 0;
        // Don't sanitize pattern_name too aggressively - it may contain slashes and special chars
        $pattern_name = isset($args['pattern_name']) ? trim($args['pattern_name']) : '';
        $mode = isset($args['mode']) ? strtolower(sanitize_text_field($args['mode'])) : 'append';

        $is_debug = defined('NIETOS_AI_DEBUG') && NIETOS_AI_DEBUG;

        if ($is_debug) {
            error_log('Nietos AI: apply_block_pattern - post_id: ' . $post_id . ', pattern_name: "' . $pattern_name . '", mode: ' . $mode);
        }

        if (!in_array($mode, array('append', 'prepend', 'replace'), true)) {
            $mode = 'append';
        }

        if (!$post_id || $pattern_name === '') {
            if ($is_debug) {
                error_log('Nietos AI: apply_block_pattern - Missing parameters');
            }
            return new WP_Error('missing_params', __('Post ID and pattern name are required.', 'nietos-ai'));
        }

        if (!current_user_can('edit_post', $post_id)) {
            if ($is_debug) {
                error_log('Nietos AI: apply_block_pattern - Permission denied');
            }
            return new WP_Error('forbidden', __('You do not have permission to edit this post.', 'nietos-ai'), array('status' => 403));
        }

        if (!class_exists('WP_Block_Patterns_Registry')) {
            if ($is_debug) {
                error_log('Nietos AI: apply_block_pattern - Registry not available');
            }
            return new WP_Error('patterns_unavailable', __('Block patterns are not available on this site.', 'nietos-ai'));
        }

        $registry = WP_Block_Patterns_Registry::get_instance();
        $all_patterns = $registry->get_all_registered();

        if ($is_debug) {
            error_log('Nietos AI: apply_block_pattern - Looking for pattern "' . $pattern_name . '" in ' . count($all_patterns) . ' registered patterns');
        }

        $pattern = $registry->get_registered($pattern_name);

        if (!$pattern || empty($pattern['content'])) {
            // Log all available pattern names for debugging
            $available_names = array_keys($all_patterns);
            if ($is_debug) {
                error_log('Nietos AI: apply_block_pattern - Pattern "' . $pattern_name . '" not found. Available: ' . implode(', ', array_slice($available_names, 0, 10)));
            }

            return new WP_Error('pattern_not_found',
                sprintf(
                    /* translators: %1$s: requested pattern name, %2$s: comma-separated list of available patterns */
                    __('The pattern "%1$s" could not be found. Available patterns: %2$s', 'nietos-ai'),
                    $pattern_name,
                    implode(', ', array_slice($available_names, 0, 5))
                )
            );
        }

        $post = get_post($post_id);

        if (!$post) {
            return new WP_Error('post_not_found', __('The requested post could not be found.', 'nietos-ai'));
        }

        $pattern_content = (string) $pattern['content'];
        $existing_content = (string) $post->post_content;
        $new_content = $pattern_content;

        if ($mode === 'append') {
            $new_content = rtrim($existing_content) . "\n\n" . $pattern_content;
        } elseif ($mode === 'prepend') {
            $new_content = $pattern_content . "\n\n" . ltrim($existing_content);
        }

        $result = wp_update_post(array(
            'ID' => $post_id,
            'post_content' => wp_slash($new_content)
        ), true);

        if (is_wp_error($result)) {
            if ($is_debug) {
                error_log('Nietos AI: apply_block_pattern - Update failed: ' . $result->get_error_message());
            }
            return $result;
        }

        if ($is_debug) {
            error_log('Nietos AI: apply_block_pattern - Successfully applied pattern "' . $pattern_name . '" to post ' . $post_id);
        }

        return array(
            'success' => true,
            'post_id' => $post_id,
            'pattern' => $pattern_name,
            'pattern_title' => $pattern['title'] ?? $pattern_name,
            'mode' => $mode,
            'message' => sprintf(
                /* translators: %1$s: pattern title, %2$s: mode (append/replace) */
                __('Pattern "%1$s" applied successfully in %2$s mode.', 'nietos-ai'),
                $pattern['title'] ?? $pattern_name,
                $mode
            )
        );
    }

    /**
     * Find media library items matching a search query
     */
    private function find_media($args) {
        if (!current_user_can('upload_files')) {
            return new WP_Error('forbidden', __('You do not have permission to view media items.', 'nietos-ai'), array('status' => 403));
        }

        $search = isset($args['search']) ? sanitize_text_field(wp_unslash($args['search'])) : '';

        $limit = isset($args['limit']) ? absint($args['limit']) : 10;
        if ($limit < 1) {
            $limit = 1;
        }
        if ($limit > 20) {
            $limit = 20;
        }

        $query_args = array(
            'post_type' => 'attachment',
            'post_status' => 'inherit',
            'posts_per_page' => $limit,
            'orderby' => 'date',
            'order' => 'DESC'
        );

        if ($search !== '') {
            $query_args['s'] = $search;
        }

        if (!empty($args['mime_type'])) {
            $query_args['post_mime_type'] = sanitize_text_field($args['mime_type']);
        }

        $media_items = get_posts($query_args);

        if (empty($media_items)) {
            return array(
                'success' => true,
                'search' => $search,
                'results' => array(),
                'total_found' => 0
            );
        }

        $results = array();

        foreach ($media_items as $item) {
            $attachment_id = $item->ID;

            if (!current_user_can('edit_post', $attachment_id)) {
                continue;
            }

            $results[] = array(
                'attachment_id' => $attachment_id,
                'title' => get_the_title($attachment_id),
                'mime_type' => get_post_mime_type($attachment_id),
                'date' => mysql2date('c', $item->post_date),
                'alt_text' => get_post_meta($attachment_id, '_wp_attachment_image_alt', true),
                'url' => wp_get_attachment_url($attachment_id),
                'edit_url' => get_edit_post_link($attachment_id, 'raw')
            );
        }

        return array(
            'success' => true,
            'search' => $search,
            'results' => $results,
            'total_found' => count($results)
        );
    }

    /**
     * List revisions for a given post
     */
    private function list_post_revisions($args) {
        $post_id = isset($args['post_id']) ? absint($args['post_id']) : 0;

        if (!$post_id) {
            return new WP_Error('no_post_id', __('Post ID is required', 'nietos-ai'));
        }

        if (!current_user_can('edit_post', $post_id)) {
            return new WP_Error('forbidden', __('You do not have permission to view revisions for this post.', 'nietos-ai'), array('status' => 403));
        }

        $limit = isset($args['limit']) ? absint($args['limit']) : 5;
        if ($limit < 1) {
            $limit = 1;
        }
        if ($limit > 20) {
            $limit = 20;
        }

        $revisions = wp_get_post_revisions($post_id, array(
            'order' => 'DESC',
            'orderby' => 'date'
        ));

        if (empty($revisions)) {
            return array(
                'success' => true,
                'post_id' => $post_id,
                'revisions' => array(),
                'total_available' => 0
            );
        }

        $results = array();
        $count = 0;

        foreach ($revisions as $revision) {
            $results[] = array(
                'revision_id' => $revision->ID,
                'author_id' => (int) $revision->post_author,
                'author_name' => get_the_author_meta('display_name', $revision->post_author),
                'modified' => mysql2date('c', $revision->post_modified),
                'modified_gmt' => mysql2date('c', $revision->post_modified_gmt),
                'excerpt' => wp_trim_words(wp_strip_all_tags($revision->post_content), 30, '…'),
                'status' => $revision->post_status
            );

            $count++;
            if ($count >= $limit) {
                break;
            }
        }

        $current_post = get_post($post_id);

        return array(
            'success' => true,
            'post_id' => $post_id,
            'current_revision_id' => $current_post ? $current_post->ID : $post_id,
            'edit_url' => get_edit_post_link($post_id, 'raw'),
            'revisions' => $results,
            'total_available' => count($revisions)
        );
    }

    /**
     * List taxonomy terms matching a search
     */
    private function list_terms($args) {
        $taxonomy = isset($args['taxonomy']) ? sanitize_key($args['taxonomy']) : '';

        if ($taxonomy === '') {
            return new WP_Error('no_taxonomy', __('Taxonomy is required', 'nietos-ai'));
        }

        $taxonomy_object = get_taxonomy($taxonomy);

        if (!$taxonomy_object) {
            return new WP_Error('invalid_taxonomy', __('The specified taxonomy does not exist.', 'nietos-ai'));
        }

        $assign_cap = 'assign_terms';
        if (isset($taxonomy_object->cap)) {
            if (is_object($taxonomy_object->cap) && isset($taxonomy_object->cap->assign_terms)) {
                $assign_cap = $taxonomy_object->cap->assign_terms;
            } elseif (is_array($taxonomy_object->cap) && isset($taxonomy_object->cap['assign_terms'])) {
                $assign_cap = $taxonomy_object->cap['assign_terms'];
            }
        }

        if (!current_user_can($assign_cap)) {
            return new WP_Error('forbidden', __('You do not have permission to view terms for this taxonomy.', 'nietos-ai'), array('status' => 403));
        }

        $limit = isset($args['limit']) ? absint($args['limit']) : 20;
        if ($limit < 1) {
            $limit = 1;
        }
        if ($limit > 50) {
            $limit = 50;
        }

        $search = isset($args['search']) ? sanitize_text_field(wp_unslash($args['search'])) : '';

        $term_query_args = array(
            'taxonomy' => $taxonomy,
            'hide_empty' => false,
            'number' => $limit,
            'orderby' => 'name',
            'order' => 'ASC'
        );

        if ($search !== '') {
            $term_query_args['search'] = $search;
        }

        $terms = get_terms($term_query_args);

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

        if (empty($terms)) {
            return array(
                'success' => true,
                'taxonomy' => $taxonomy,
                'results' => array(),
                'total_found' => 0
            );
        }

        $results = array();
        foreach ($terms as $term) {
            $edit_link = get_edit_term_link($term->term_id, $taxonomy);
            if (is_wp_error($edit_link)) {
                $edit_link = '';
            }

            $results[] = array(
                'term_id' => $term->term_id,
                'name' => $term->name,
                'slug' => $term->slug,
                'count' => (int) $term->count,
                'description' => $term->description,
                'edit_url' => $edit_link
            );
        }

        return array(
            'success' => true,
            'taxonomy' => $taxonomy,
            'results' => $results,
            'total_found' => count($results)
        );
    }

    /**
     * Restore a previous revision of a post
     */
    private function restore_post_revision($args) {
        $post_id = isset($args['post_id']) ? absint($args['post_id']) : 0;
        $revision_id = isset($args['revision_id']) ? absint($args['revision_id']) : 0;

        if (!$post_id) {
            return new WP_Error('no_post_id', __('Post ID is required', 'nietos-ai'));
        }

        if (!current_user_can('edit_post', $post_id)) {
            return new WP_Error('forbidden', __('You do not have permission to edit this post.', 'nietos-ai'), array('status' => 403));
        }

        $revisions = wp_get_post_revisions($post_id, array(
            'order' => 'DESC',
            'orderby' => 'date'
        ));

        if (empty($revisions)) {
            return new WP_Error('no_revisions', __('No revisions available for this post.', 'nietos-ai'));
        }

        if ($revision_id) {
            if (!isset($revisions[$revision_id])) {
                return new WP_Error('revision_not_found', __('The specified revision could not be found for this post.', 'nietos-ai'));
            }
            $target_revision = $revisions[$revision_id];
        } else {
            $target_revision = reset($revisions);
            $revision_id = $target_revision->ID;
        }

        require_once ABSPATH . 'wp-admin/includes/revision.php';

        $restored_post_id = wp_restore_post_revision($revision_id);

        if (!$restored_post_id || is_wp_error($restored_post_id)) {
            $error = is_wp_error($restored_post_id) ? $restored_post_id : new WP_Error('restore_failed', __('Failed to restore the selected revision.', 'nietos-ai'));
            return $error;
        }

        return array(
            'success' => true,
            'post_id' => $post_id,
            'restored_revision_id' => $revision_id,
            'revision_date' => mysql2date('c', $target_revision->post_modified),
            'edit_url' => get_edit_post_link($post_id, 'raw'),
            'message' => sprintf(
                /* translators: %s: revision date and time */
                __('Restored revision from %s.', 'nietos-ai'),
                mysql2date(get_option('date_format') . ' ' . get_option('time_format'), $target_revision->post_modified)
            )
        );
    }

    /**
     * Delete post
     */
    private function delete_post($args) {
        $post_id = isset($args['post_id']) ? absint($args['post_id']) : 0;
        $confirmed = isset($args['confirm']) ? (bool) $args['confirm'] : false;

        if (!$post_id || !$confirmed) {
            return new WP_Error('confirmation_required', __('Post ID and confirmation are required to delete a post.', 'nietos-ai'));
        }

        if (!current_user_can('delete_post', $post_id)) {
            return new WP_Error('forbidden', __('You do not have permission to delete this post.', 'nietos-ai'), array('status' => 403));
        }

        $post = get_post($post_id);
        if (!$post) {
            return new WP_Error('post_not_found', __('The requested post could not be found.', 'nietos-ai'));
        }

        $result = wp_delete_post($post_id, true);

        if (!$result) {
            return new WP_Error('delete_failed', __('Failed to delete post', 'nietos-ai'));
        }

        return array(
            'success' => true,
            'post_id' => $post_id,
            'message' => __('Post deleted successfully', 'nietos-ai')
        );
    }
    /**
     * Upload media from URL
     */
    private function upload_media($args) {
        if (!current_user_can('upload_files')) {
            return new WP_Error('forbidden', __('You do not have permission to upload files.', 'nietos-ai'), array('status' => 403));
        }

        $url = isset($args['url']) ? esc_url_raw($args['url']) : '';
        if (empty($url)) {
            return new WP_Error('no_url', __('A media URL is required.', 'nietos-ai'));
        }

        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';

        $tmp_file = download_url($url);
        if (is_wp_error($tmp_file)) {
            return new WP_Error('download_failed', __('Failed to download the media asset.', 'nietos-ai'));
        }

        $filename = !empty($args['filename']) ? $args['filename'] : basename(wp_parse_url($url, PHP_URL_PATH));
        if (!$filename) {
            $filename = 'nietos-ai-upload-' . time();
        }

        $file_array = array(
            'name' => sanitize_file_name($filename),
            'tmp_name' => $tmp_file
        );

        $attachment_id = media_handle_sideload($file_array, 0, sanitize_text_field($args['description'] ?? ''));

        if (is_wp_error($attachment_id)) {
            wp_delete_file($tmp_file);
            return new WP_Error('upload_failed', $attachment_id->get_error_message());
        }

        // Update metadata
        if (!empty($args['title'])) {
            wp_update_post(array(
                'ID' => $attachment_id,
                'post_title' => sanitize_text_field($args['title'])
            ));
        }

        if (!empty($args['caption'])) {
            wp_update_post(array(
                'ID' => $attachment_id,
                'post_excerpt' => sanitize_textarea_field($args['caption'])
            ));
        }

        if (!empty($args['description'])) {
            wp_update_post(array(
                'ID' => $attachment_id,
                'post_content' => wp_kses_post($args['description'])
            ));
        }

        if (!empty($args['alt_text'])) {
            update_post_meta($attachment_id, '_wp_attachment_image_alt', sanitize_text_field($args['alt_text']));
        }

        return array(
            'success' => true,
            'attachment_id' => $attachment_id,
            'url' => wp_get_attachment_url($attachment_id)
        );
    }

    /**
     * Update media metadata
     */
    private function update_media_metadata($args) {
        $attachment_id = isset($args['attachment_id']) ? absint($args['attachment_id']) : 0;
        if (!$attachment_id) {
            return new WP_Error('no_attachment_id', __('Attachment ID is required.', 'nietos-ai'));
        }

        if (!current_user_can('edit_post', $attachment_id)) {
            return new WP_Error('forbidden', __('You do not have permission to edit this media item.', 'nietos-ai'), array('status' => 403));
        }

        $attachment = get_post($attachment_id);
        if (!$attachment || $attachment->post_type !== 'attachment') {
            return new WP_Error('invalid_attachment', __('The specified attachment could not be found.', 'nietos-ai'));
        }

        $update = array('ID' => $attachment_id);
        $should_update_post = false;

        if (isset($args['title'])) {
            $update['post_title'] = sanitize_text_field($args['title']);
            $should_update_post = true;
        }

        if (isset($args['caption'])) {
            $update['post_excerpt'] = sanitize_textarea_field($args['caption']);
            $should_update_post = true;
        }

        if (isset($args['description'])) {
            $update['post_content'] = wp_kses_post($args['description']);
            $should_update_post = true;
        }

        if ($should_update_post) {
            $result = wp_update_post($update, true);
            if (is_wp_error($result)) {
                return new WP_Error('update_failed', $result->get_error_message());
            }
        }

        if (isset($args['alt_text'])) {
            update_post_meta($attachment_id, '_wp_attachment_image_alt', sanitize_text_field($args['alt_text']));
        }

        return array(
            'success' => true,
            'attachment_id' => $attachment_id
        );
    }

    /**
     * Set featured image for a post
     */
    private function set_featured_image($args) {
        $post_id = isset($args['post_id']) ? absint($args['post_id']) : 0;
        $attachment_id = isset($args['attachment_id']) ? absint($args['attachment_id']) : 0;

        if (!$post_id || !$attachment_id) {
            return new WP_Error('missing_parameters', __('Post ID and attachment ID are required.', 'nietos-ai'));
        }

        if (!current_user_can('edit_post', $post_id)) {
            return new WP_Error('forbidden', __('You do not have permission to edit this post.', 'nietos-ai'), array('status' => 403));
        }

        $attachment = get_post($attachment_id);
        if (!$attachment || $attachment->post_type !== 'attachment') {
            return new WP_Error('invalid_attachment', __('The specified attachment could not be found.', 'nietos-ai'));
        }

        $result = set_post_thumbnail($post_id, $attachment_id);

        if (!$result) {
            return new WP_Error('set_thumbnail_failed', __('Failed to set the featured image.', 'nietos-ai'));
        }

        return array(
            'success' => true,
            'post_id' => $post_id,
            'attachment_id' => $attachment_id,
            'thumbnail_url' => wp_get_attachment_image_url($attachment_id, 'full')
        );
    }

    /**
     * Create a new user
     */
    private function create_user($args) {
        if (!current_user_can('create_users')) {
            return new WP_Error('forbidden', __('You do not have permission to create users.', 'nietos-ai'), array('status' => 403));
        }

        $username = isset($args['username']) ? sanitize_user($args['username'], true) : '';
        $email = isset($args['email']) ? sanitize_email($args['email']) : '';

        if (empty($username) || empty($email)) {
            return new WP_Error('missing_fields', __('Username and email are required to create a user.', 'nietos-ai'));
        }

        if (!is_email($email)) {
            return new WP_Error('invalid_email', __('Please provide a valid email address.', 'nietos-ai'));
        }

        $role = isset($args['role']) ? sanitize_key($args['role']) : get_option('default_role', 'subscriber');
        if (!get_role($role)) {
            return new WP_Error('invalid_role', __('The specified role is not valid.', 'nietos-ai'));
        }

        $password = isset($args['password']) && !empty($args['password'])
            ? $args['password']
            : wp_generate_password(20, true);

        $user_data = array(
            'user_login' => $username,
            'user_email' => $email,
            'user_pass' => $password,
            'role' => $role,
            'first_name' => isset($args['first_name']) ? sanitize_text_field($args['first_name']) : '',
            'last_name' => isset($args['last_name']) ? sanitize_text_field($args['last_name']) : '',
            'display_name' => isset($args['display_name']) ? sanitize_text_field($args['display_name']) : ''
        );

        $user_id = wp_insert_user($user_data);

        if (is_wp_error($user_id)) {
            return new WP_Error('user_creation_failed', $user_id->get_error_message());
        }

        return array(
            'success' => true,
            'user_id' => $user_id,
            'email' => $email,
            'role' => $role,
            'password_generated' => empty($args['password']),
            'temporary_password' => empty($args['password']) ? $password : null
        );
    }

    /**
     * Update user details
     */
    private function update_user($args) {
        $user_id = isset($args['user_id']) ? absint($args['user_id']) : 0;
        if (!$user_id) {
            return new WP_Error('no_user_id', __('User ID is required.', 'nietos-ai'));
        }

        if (!current_user_can('edit_user', $user_id)) {
            return new WP_Error('forbidden', __('You do not have permission to edit this user.', 'nietos-ai'), array('status' => 403));
        }

        $user = get_userdata($user_id);
        if (!$user) {
            return new WP_Error('user_not_found', __('The specified user could not be found.', 'nietos-ai'));
        }

        $update = array('ID' => $user_id);

        if (isset($args['email'])) {
            $email = sanitize_email($args['email']);
            if (!is_email($email)) {
                return new WP_Error('invalid_email', __('Please provide a valid email address.', 'nietos-ai'));
            }
            $update['user_email'] = $email;
        }

        if (isset($args['first_name'])) {
            $update['first_name'] = sanitize_text_field($args['first_name']);
        }

        if (isset($args['last_name'])) {
            $update['last_name'] = sanitize_text_field($args['last_name']);
        }

        if (isset($args['display_name'])) {
            $update['display_name'] = sanitize_text_field($args['display_name']);
        }

        if (isset($args['password']) && !empty($args['password'])) {
            $update['user_pass'] = $args['password'];
        }

        $result = wp_update_user($update);

        if (is_wp_error($result)) {
            return new WP_Error('user_update_failed', $result->get_error_message());
        }

        return array(
            'success' => true,
            'user_id' => $user_id
        );
    }

    /**
     * Change user role
     */
    private function change_user_role($args) {
        $user_id = isset($args['user_id']) ? absint($args['user_id']) : 0;
        $role = isset($args['role']) ? sanitize_key($args['role']) : '';

        if (!$user_id || empty($role)) {
            return new WP_Error('missing_fields', __('User ID and role are required.', 'nietos-ai'));
        }

        if (!current_user_can('promote_user', $user_id)) {
            return new WP_Error('forbidden', __('You do not have permission to change this user\'s role.', 'nietos-ai'), array('status' => 403));
        }

        if (!get_role($role)) {
            return new WP_Error('invalid_role', __('The specified role is not valid.', 'nietos-ai'));
        }

        $user = get_userdata($user_id);
        if (!$user) {
            return new WP_Error('user_not_found', __('The specified user could not be found.', 'nietos-ai'));
        }

        $user->set_role($role);

        return array(
            'success' => true,
            'user_id' => $user_id,
            'role' => $role
        );
    }

    /**
     * Delete a user
     */
    private function delete_user($args) {
        $user_id = isset($args['user_id']) ? absint($args['user_id']) : 0;
        $confirm = isset($args['confirm']) ? (bool) $args['confirm'] : false;

        if (!$user_id || !$confirm) {
            return new WP_Error('confirmation_required', __('User ID and confirmation are required to delete a user.', 'nietos-ai'));
        }

        if (!current_user_can('delete_user', $user_id)) {
            return new WP_Error('forbidden', __('You do not have permission to delete this user.', 'nietos-ai'), array('status' => 403));
        }

        $reassign_to = isset($args['reassign_to']) ? absint($args['reassign_to']) : 0;
        if ($reassign_to && !get_userdata($reassign_to)) {
            return new WP_Error('invalid_reassign', __('The reassignment user could not be found.', 'nietos-ai'));
        }

        $result = $reassign_to
            ? wp_delete_user($user_id, $reassign_to)
            : wp_delete_user($user_id);

        if (!$result) {
            return new WP_Error('delete_failed', __('Failed to delete the user.', 'nietos-ai'));
        }

        return array(
            'success' => true,
            'user_id' => $user_id,
            'reassigned_to' => $reassign_to ?: null
        );
    }

    /**
     * Update general site settings
     */
    private function update_site_settings($args) {
        if (!current_user_can('manage_options')) {
            return new WP_Error('forbidden', __('You do not have permission to update site settings.', 'nietos-ai'), array('status' => 403));
        }

        $updates = array();

        if (isset($args['site_title'])) {
            $updates['blogname'] = sanitize_text_field($args['site_title']);
        }

        if (isset($args['tagline'])) {
            $updates['blogdescription'] = sanitize_text_field($args['tagline']);
        }

        if (isset($args['timezone'])) {
            $timezone = sanitize_text_field($args['timezone']);
            if (in_array($timezone, timezone_identifiers_list(), true)) {
                $updates['timezone_string'] = $timezone;
            } else {
                return new WP_Error('invalid_timezone', __('The timezone provided is not valid.', 'nietos-ai'));
            }
        }

        if (isset($args['date_format'])) {
            $updates['date_format'] = sanitize_text_field($args['date_format']);
        }

        if (isset($args['time_format'])) {
            $updates['time_format'] = sanitize_text_field($args['time_format']);
        }

        foreach ($updates as $option => $value) {
            update_option($option, $value);
        }

        return array(
            'success' => true,
            'updated' => array_keys($updates)
        );
    }

    /**
     * Update discussion and comment settings
     */
    private function update_discussion_settings($args) {
        if (!current_user_can('manage_options')) {
            return new WP_Error('forbidden', __('You do not have permission to update discussion settings.', 'nietos-ai'), array('status' => 403));
        }

        $updated = array();

        if (isset($args['require_account'])) {
            update_option('comment_registration', (bool) $args['require_account']);
            $updated[] = 'comment_registration';
        }

        if (isset($args['auto_close_days'])) {
            $days = absint($args['auto_close_days']);
            update_option('close_comments_for_old_posts', $days > 0);
            update_option('close_comments_days_old', $days);
            $updated[] = 'close_comments_for_old_posts';
            $updated[] = 'close_comments_days_old';
        }

        if (isset($args['hold_moderation_keywords'])) {
            update_option('moderation_keys', sanitize_textarea_field($args['hold_moderation_keywords']));
            $updated[] = 'moderation_keys';
        }

        if (isset($args['comment_moderation'])) {
            update_option('comment_moderation', (bool) $args['comment_moderation']);
            $updated[] = 'comment_moderation';
        }

        if (isset($args['comment_max_links'])) {
            update_option('comment_max_links', absint($args['comment_max_links']));
            $updated[] = 'comment_max_links';
        }

        return array(
            'success' => true,
            'updated' => $updated
        );
    }

    /**
     * Create taxonomy term
     */
    private function create_term($args) {
        $taxonomy = isset($args['taxonomy']) ? sanitize_key($args['taxonomy']) : 'category';
        $taxonomy_object = get_taxonomy($taxonomy);

        if (!$taxonomy_object) {
            return new WP_Error('invalid_taxonomy', __('The specified taxonomy does not exist.', 'nietos-ai'));
        }

        $capability = isset($taxonomy_object->cap->manage_terms) ? $taxonomy_object->cap->manage_terms : 'manage_categories';
        if (!current_user_can($capability)) {
            return new WP_Error('forbidden', __('You do not have permission to manage terms for this taxonomy.', 'nietos-ai'), array('status' => 403));
        }

        $name = isset($args['name']) ? sanitize_text_field($args['name']) : '';
        if (empty($name)) {
            return new WP_Error('missing_name', __('A term name is required.', 'nietos-ai'));
        }

        $term_args = array();

        if (!empty($args['slug'])) {
            $term_args['slug'] = sanitize_title($args['slug']);
        }

        if (!empty($args['description'])) {
            $term_args['description'] = sanitize_textarea_field($args['description']);
        }

        if (isset($args['parent']) && $taxonomy_object->hierarchical) {
            $term_args['parent'] = absint($args['parent']);
        }

        $result = wp_insert_term($name, $taxonomy, $term_args);

        if (is_wp_error($result)) {
            return new WP_Error('term_creation_failed', $result->get_error_message());
        }

        return array(
            'success' => true,
            'term_id' => $result['term_id'],
            'taxonomy' => $taxonomy
        );
    }

    /**
     * Update taxonomy term
     */
    private function update_term($args) {
        $term_id = isset($args['term_id']) ? absint($args['term_id']) : 0;
        if (!$term_id) {
            return new WP_Error('no_term_id', __('Term ID is required.', 'nietos-ai'));
        }

        $term = get_term($term_id);
        if (!$term || is_wp_error($term)) {
            return new WP_Error('term_not_found', __('The specified term could not be found.', 'nietos-ai'));
        }

        $taxonomy = isset($args['taxonomy']) ? sanitize_key($args['taxonomy']) : $term->taxonomy;
        $taxonomy_object = get_taxonomy($taxonomy);

        if (!$taxonomy_object) {
            return new WP_Error('invalid_taxonomy', __('The specified taxonomy does not exist.', 'nietos-ai'));
        }

        $capability = isset($taxonomy_object->cap->edit_terms) ? $taxonomy_object->cap->edit_terms : 'manage_categories';
        if (!current_user_can($capability)) {
            return new WP_Error('forbidden', __('You do not have permission to edit terms for this taxonomy.', 'nietos-ai'), array('status' => 403));
        }

        $term_args = array();

        if (isset($args['name'])) {
            $term_args['name'] = sanitize_text_field($args['name']);
        }

        if (isset($args['slug'])) {
            $term_args['slug'] = sanitize_title($args['slug']);
        }

        if (isset($args['description'])) {
            $term_args['description'] = sanitize_textarea_field($args['description']);
        }

        if (isset($args['parent']) && $taxonomy_object->hierarchical) {
            $term_args['parent'] = absint($args['parent']);
        }

        if (empty($term_args)) {
            return new WP_Error('nothing_to_update', __('No term fields were provided to update.', 'nietos-ai'));
        }

        $result = wp_update_term($term_id, $taxonomy, $term_args);

        if (is_wp_error($result)) {
            return new WP_Error('term_update_failed', $result->get_error_message());
        }

        return array(
            'success' => true,
            'term_id' => $term_id,
            'taxonomy' => $taxonomy
        );
    }

    /**
     * Delete taxonomy term
     */
    private function delete_term($args) {
        $term_id = isset($args['term_id']) ? absint($args['term_id']) : 0;
        $taxonomy = isset($args['taxonomy']) ? sanitize_key($args['taxonomy']) : '';
        $confirm = isset($args['confirm']) ? (bool) $args['confirm'] : false;

        if (!$term_id || empty($taxonomy) || !$confirm) {
            return new WP_Error('confirmation_required', __('Term ID, taxonomy, and confirmation are required.', 'nietos-ai'));
        }

        $taxonomy_object = get_taxonomy($taxonomy);
        if (!$taxonomy_object) {
            return new WP_Error('invalid_taxonomy', __('The specified taxonomy does not exist.', 'nietos-ai'));
        }

        $capability = isset($taxonomy_object->cap->delete_terms) ? $taxonomy_object->cap->delete_terms : 'manage_categories';
        if (!current_user_can($capability)) {
            return new WP_Error('forbidden', __('You do not have permission to delete terms for this taxonomy.', 'nietos-ai'), array('status' => 403));
        }

        $result = wp_delete_term($term_id, $taxonomy);

        if (is_wp_error($result)) {
            return new WP_Error('term_deletion_failed', $result->get_error_message());
        }

        if (!$result) {
            return new WP_Error('term_deletion_failed', __('Failed to delete the term.', 'nietos-ai'));
        }

        return array(
            'success' => true,
            'term_id' => $term_id,
            'taxonomy' => $taxonomy
        );
    }

    /**
     * Assign taxonomy terms to a post
     */
    private function assign_terms_to_post($args) {
        $post_id = isset($args['post_id']) ? absint($args['post_id']) : 0;
        if (!$post_id) {
            return new WP_Error('no_post_id', __('Post ID is required.', 'nietos-ai'));
        }

        if (!current_user_can('edit_post', $post_id)) {
            return new WP_Error('forbidden', __('You do not have permission to edit this post.', 'nietos-ai'), array('status' => 403));
        }

        $taxonomy = isset($args['taxonomy']) ? sanitize_key($args['taxonomy']) : 'category';
        $taxonomy_object = get_taxonomy($taxonomy);
        if (!$taxonomy_object) {
            return new WP_Error('invalid_taxonomy', __('The specified taxonomy does not exist.', 'nietos-ai'));
        }

        $term_ids = isset($args['term_ids']) && is_array($args['term_ids']) ? array_map('absint', $args['term_ids']) : array();
        $term_ids = array_filter($term_ids);

        if (empty($term_ids)) {
            return new WP_Error('no_terms', __('You must provide at least one term ID.', 'nietos-ai'));
        }

        $append = isset($args['append']) ? (bool) $args['append'] : false;

        $result = wp_set_object_terms($post_id, $term_ids, $taxonomy, $append);

        if (is_wp_error($result)) {
            return new WP_Error('term_assignment_failed', $result->get_error_message());
        }

        $term_taxonomy_ids = array_map('intval', (array) $result);

        $assigned_terms = wp_get_object_terms(
            $post_id,
            $taxonomy,
            array(
                'fields' => 'all'
            )
        );

        if (is_wp_error($assigned_terms)) {
            return new WP_Error('term_assignment_failed', $assigned_terms->get_error_message());
        }

        $assigned_terms_data = array_map(
            function ($term) {
                return array(
                    'term_id' => (int) $term->term_id,
                    'name' => $term->name,
                    'slug' => $term->slug,
                    'description' => $term->description,
                    'count' => (int) $term->count,
                    'taxonomy' => $term->taxonomy
                );
            },
            $assigned_terms
        );

        return array(
            'success' => true,
            'post_id' => $post_id,
            'taxonomy' => $taxonomy,
            'assigned_terms' => $assigned_terms_data,
            'assigned_term_ids' => array_map(
                'intval',
                wp_list_pluck($assigned_terms_data, 'term_id')
            ),
            'assigned_term_taxonomy_ids' => $term_taxonomy_ids
        );
    }

    /**
     * Approve a comment
     */
    private function approve_comment($args) {
        $comment_id = isset($args['comment_id']) ? absint($args['comment_id']) : 0;
        if (!$comment_id) {
            return new WP_Error('no_comment_id', __('Comment ID is required.', 'nietos-ai'));
        }

        if (!current_user_can('moderate_comments')) {
            return new WP_Error('forbidden', __('You do not have permission to moderate comments.', 'nietos-ai'), array('status' => 403));
        }

        $comment = get_comment($comment_id);
        if (!$comment) {
            return new WP_Error('comment_not_found', __('The specified comment could not be found.', 'nietos-ai'));
        }

        $result = wp_set_comment_status($comment_id, 'approve', true);

        if (is_wp_error($result)) {
            return new WP_Error('approval_failed', $result->get_error_message());
        }

        return array(
            'success' => true,
            'comment_id' => $comment_id,
            'status' => 'approved'
        );
    }

    /**
     * Trash a comment
     */
    private function trash_comment($args) {
        $comment_id = isset($args['comment_id']) ? absint($args['comment_id']) : 0;
        $confirm = isset($args['confirm']) ? (bool) $args['confirm'] : false;

        if (!$comment_id || !$confirm) {
            return new WP_Error('confirmation_required', __('Comment ID and confirmation are required.', 'nietos-ai'));
        }

        if (!current_user_can('moderate_comments')) {
            return new WP_Error('forbidden', __('You do not have permission to moderate comments.', 'nietos-ai'), array('status' => 403));
        }

        $comment = get_comment($comment_id);
        if (!$comment) {
            return new WP_Error('comment_not_found', __('The specified comment could not be found.', 'nietos-ai'));
        }

        $result = wp_trash_comment($comment_id);
        if (!$result) {
            return new WP_Error('trash_failed', __('Failed to trash the comment.', 'nietos-ai'));
        }

        return array(
            'success' => true,
            'comment_id' => $comment_id,
            'status' => 'trashed'
        );
    }

    /**
     * Reply to a comment
     */
    private function reply_to_comment($args) {
        $comment_id = isset($args['comment_id']) ? absint($args['comment_id']) : 0;
        $content = isset($args['content']) ? wp_kses_post($args['content']) : '';

        if (!$comment_id || empty($content)) {
            return new WP_Error('missing_fields', __('Comment ID and reply content are required.', 'nietos-ai'));
        }

        if (!current_user_can('moderate_comments')) {
            return new WP_Error('forbidden', __('You do not have permission to reply to comments.', 'nietos-ai'), array('status' => 403));
        }

        $parent_comment = get_comment($comment_id);
        if (!$parent_comment) {
            return new WP_Error('comment_not_found', __('The specified comment could not be found.', 'nietos-ai'));
        }

        $current_user = wp_get_current_user();
        $commentdata = array(
            'comment_post_ID' => $parent_comment->comment_post_ID,
            'comment_parent' => $comment_id,
            'comment_content' => $content,
            'user_id' => $current_user->ID,
            'comment_author' => $current_user->display_name,
            'comment_author_email' => $current_user->user_email,
            'comment_author_url' => $current_user->user_url,
            'comment_approved' => 1
        );

        $reply_id = wp_insert_comment($commentdata);

        if (!$reply_id || is_wp_error($reply_id)) {
            return new WP_Error('reply_failed', __('Failed to create the comment reply.', 'nietos-ai'));
        }

        return array(
            'success' => true,
            'comment_id' => $reply_id,
            'parent_id' => $comment_id
        );
    }

    /**
     * Create navigation menu
     */
    private function create_menu($args) {
        if (!current_user_can('edit_theme_options')) {
            return new WP_Error('forbidden', __('You do not have permission to manage menus.', 'nietos-ai'), array('status' => 403));
        }

        $name = isset($args['name']) ? sanitize_text_field($args['name']) : '';
        if (empty($name)) {
            return new WP_Error('missing_name', __('A menu name is required.', 'nietos-ai'));
        }

        require_once ABSPATH . 'wp-admin/includes/nav-menu.php';

        $menu_args = array();

        if (!empty($args['slug'])) {
            $menu_args['slug'] = sanitize_title($args['slug']);
        }

        if (!empty($args['description'])) {
            $menu_args['description'] = sanitize_textarea_field($args['description']);
        }

        $menu_id = wp_create_nav_menu($name, $menu_args);

        if (is_wp_error($menu_id)) {
            return new WP_Error('menu_creation_failed', $menu_id->get_error_message());
        }

        return array(
            'success' => true,
            'menu_id' => (int) $menu_id,
            'name' => $name
        );
    }

    /**
     * Update navigation menu
     */
    private function update_menu($args) {
        if (!current_user_can('edit_theme_options')) {
            return new WP_Error('forbidden', __('You do not have permission to manage menus.', 'nietos-ai'), array('status' => 403));
        }

        $menu_id = isset($args['menu_id']) ? absint($args['menu_id']) : 0;
        if (!$menu_id) {
            return new WP_Error('no_menu_id', __('Menu ID is required.', 'nietos-ai'));
        }

        $menu = wp_get_nav_menu_object($menu_id);
        if (!$menu) {
            return new WP_Error('menu_not_found', __('The specified menu could not be found.', 'nietos-ai'));
        }

        require_once ABSPATH . 'wp-admin/includes/nav-menu.php';

        $menu_args = array();

        if (isset($args['name'])) {
            $menu_args['menu-name'] = sanitize_text_field($args['name']);
        }

        if (isset($args['slug'])) {
            $menu_args['menu-slug'] = sanitize_title($args['slug']);
        }

        if (isset($args['description'])) {
            $menu_args['description'] = sanitize_textarea_field($args['description']);
        }

        if (empty($menu_args)) {
            return new WP_Error('nothing_to_update', __('No menu fields were provided to update.', 'nietos-ai'));
        }

        $result = wp_update_nav_menu_object($menu_id, $menu_args);

        if (is_wp_error($result)) {
            return new WP_Error('menu_update_failed', $result->get_error_message());
        }

        return array(
            'success' => true,
            'menu_id' => $menu_id
        );
    }

    /**
     * Delete navigation menu
     */
    private function delete_menu($args) {
        if (!current_user_can('edit_theme_options')) {
            return new WP_Error('forbidden', __('You do not have permission to manage menus.', 'nietos-ai'), array('status' => 403));
        }

        $menu_id = isset($args['menu_id']) ? absint($args['menu_id']) : 0;
        $confirm = isset($args['confirm']) ? (bool) $args['confirm'] : false;

        if (!$menu_id || !$confirm) {
            return new WP_Error('confirmation_required', __('Menu ID and confirmation are required.', 'nietos-ai'));
        }

        require_once ABSPATH . 'wp-admin/includes/nav-menu.php';

        $result = wp_delete_nav_menu($menu_id);

        if (!$result || is_wp_error($result)) {
            $message = is_wp_error($result) ? $result->get_error_message() : __('Failed to delete the menu.', 'nietos-ai');
            return new WP_Error('menu_deletion_failed', $message);
        }

        return array(
            'success' => true,
            'menu_id' => $menu_id
        );
    }

    /**
     * Assign menu to theme location
     */
    private function assign_menu_location($args) {
        if (!current_user_can('edit_theme_options')) {
            return new WP_Error('forbidden', __('You do not have permission to manage menus.', 'nietos-ai'), array('status' => 403));
        }

        $menu_id = isset($args['menu_id']) ? absint($args['menu_id']) : 0;
        $location = isset($args['location']) ? sanitize_key($args['location']) : '';

        if (!$menu_id || empty($location)) {
            return new WP_Error('missing_fields', __('Menu ID and location are required.', 'nietos-ai'));
        }

        $menu = wp_get_nav_menu_object($menu_id);
        if (!$menu) {
            return new WP_Error('menu_not_found', __('The specified menu could not be found.', 'nietos-ai'));
        }

        $registered_locations = get_registered_nav_menus();
        if (!isset($registered_locations[$location])) {
            return new WP_Error('invalid_location', __('The specified menu location is not registered by the theme.', 'nietos-ai'));
        }

        $locations = get_theme_mod('nav_menu_locations', array());
        $locations[$location] = $menu_id;
        wp_set_nav_menu_locations($locations);

        return array(
            'success' => true,
            'menu_id' => $menu_id,
            'location' => $location
        );
    }

    /**
     * Add item to navigation menu
     */
    private function add_menu_item($args) {
        if (!current_user_can('edit_theme_options')) {
            return new WP_Error('forbidden', __('You do not have permission to manage menus.', 'nietos-ai'), array('status' => 403));
        }

        $menu_id = isset($args['menu_id']) ? absint($args['menu_id']) : 0;
        if (!$menu_id) {
            return new WP_Error('no_menu_id', __('Menu ID is required.', 'nietos-ai'));
        }

        $menu = wp_get_nav_menu_object($menu_id);
        if (!$menu) {
            return new WP_Error('menu_not_found', __('The specified menu could not be found.', 'nietos-ai'));
        }

        $title = sanitize_text_field($args['title'] ?? '');
        if (empty($title)) {
            return new WP_Error('missing_title', __('Menu item title is required.', 'nietos-ai'));
        }

        require_once ABSPATH . 'wp-admin/includes/nav-menu.php';

        $type = isset($args['type']) ? sanitize_key($args['type']) : 'custom';
        $menu_item_data = array(
            'menu-item-title' => $title,
            'menu-item-status' => 'publish'
        );

        if ($type === 'post_type') {
            $object_id = absint($args['object_id'] ?? 0);
            $object = sanitize_key($args['object'] ?? '');
            if (!$object_id || empty($object)) {
                return new WP_Error('invalid_object', __('Post type menu items require object ID and object type.', 'nietos-ai'));
            }
            $menu_item_data['menu-item-type'] = 'post_type';
            $menu_item_data['menu-item-object-id'] = $object_id;
            $menu_item_data['menu-item-object'] = $object;
        } elseif ($type === 'taxonomy') {
            $object_id = absint($args['object_id'] ?? 0);
            $object = sanitize_key($args['object'] ?? '');
            if (!$object_id || empty($object)) {
                return new WP_Error('invalid_object', __('Taxonomy menu items require object ID and taxonomy.', 'nietos-ai'));
            }
            $menu_item_data['menu-item-type'] = 'taxonomy';
            $menu_item_data['menu-item-object-id'] = $object_id;
            $menu_item_data['menu-item-object'] = $object;
        } else {
            $url = isset($args['url']) ? esc_url_raw($args['url']) : '';
            if (empty($url)) {
                return new WP_Error('missing_url', __('Custom menu items require a URL.', 'nietos-ai'));
            }
            $menu_item_data['menu-item-type'] = 'custom';
            $menu_item_data['menu-item-url'] = $url;
        }

        if (isset($args['parent_id'])) {
            $menu_item_data['menu-item-parent-id'] = absint($args['parent_id']);
        }

        if (isset($args['position'])) {
            $menu_item_data['menu-item-position'] = absint($args['position']);
        }

        $item_id = wp_update_nav_menu_item($menu_id, 0, $menu_item_data);

        if (is_wp_error($item_id)) {
            return new WP_Error('menu_item_creation_failed', $item_id->get_error_message());
        }

        return array(
            'success' => true,
            'menu_id' => $menu_id,
            'item_id' => (int) $item_id
        );
    }

    /**
     * Update navigation menu item
     */
    private function update_menu_item($args) {
        if (!current_user_can('edit_theme_options')) {
            return new WP_Error('forbidden', __('You do not have permission to manage menus.', 'nietos-ai'), array('status' => 403));
        }

        $menu_id = isset($args['menu_id']) ? absint($args['menu_id']) : 0;
        $item_id = isset($args['item_id']) ? absint($args['item_id']) : 0;

        if (!$menu_id || !$item_id) {
            return new WP_Error('missing_fields', __('Menu ID and item ID are required.', 'nietos-ai'));
        }

        $menu = wp_get_nav_menu_object($menu_id);
        if (!$menu) {
            return new WP_Error('menu_not_found', __('The specified menu could not be found.', 'nietos-ai'));
        }

        $item_post = get_post($item_id);
        if (!$item_post || $item_post->post_type !== 'nav_menu_item') {
            return new WP_Error('menu_item_not_found', __('The specified menu item could not be found.', 'nietos-ai'));
        }

        require_once ABSPATH . 'wp-admin/includes/nav-menu.php';

        $menu_item_data = array(
            'menu-item-db-id' => $item_id,
            'menu-item-status' => 'publish'
        );

        if (isset($args['title'])) {
            $menu_item_data['menu-item-title'] = sanitize_text_field($args['title']);
        }

        if (isset($args['url'])) {
            $menu_item_data['menu-item-url'] = esc_url_raw($args['url']);
        }

        if (isset($args['parent_id'])) {
            $menu_item_data['menu-item-parent-id'] = absint($args['parent_id']);
        }

        if (isset($args['position'])) {
            $menu_item_data['menu-item-position'] = absint($args['position']);
        }

        if (count($menu_item_data) === 1) { // only contains status
            return new WP_Error('nothing_to_update', __('No menu item fields were provided to update.', 'nietos-ai'));
        }

        $result = wp_update_nav_menu_item($menu_id, $item_id, $menu_item_data);

        if (is_wp_error($result)) {
            return new WP_Error('menu_item_update_failed', $result->get_error_message());
        }

        return array(
            'success' => true,
            'menu_id' => $menu_id,
            'item_id' => $item_id
        );
    }

    /**
     * Delete navigation menu item
     */
    private function delete_menu_item($args) {
        if (!current_user_can('edit_theme_options')) {
            return new WP_Error('forbidden', __('You do not have permission to manage menus.', 'nietos-ai'), array('status' => 403));
        }

        $menu_id = isset($args['menu_id']) ? absint($args['menu_id']) : 0;
        $item_id = isset($args['item_id']) ? absint($args['item_id']) : 0;
        $confirm = isset($args['confirm']) ? (bool) $args['confirm'] : false;

        if (!$menu_id || !$item_id || !$confirm) {
            return new WP_Error('confirmation_required', __('Menu ID, item ID, and confirmation are required.', 'nietos-ai'));
        }

        $menu = wp_get_nav_menu_object($menu_id);
        if (!$menu) {
            return new WP_Error('menu_not_found', __('The specified menu could not be found.', 'nietos-ai'));
        }

        $item_post = get_post($item_id);
        if (!$item_post || $item_post->post_type !== 'nav_menu_item') {
            return new WP_Error('menu_item_not_found', __('The specified menu item could not be found.', 'nietos-ai'));
        }

        require_once ABSPATH . 'wp-admin/includes/nav-menu.php';

        $result = wp_delete_post($item_id, true);

        if (!$result) {
            return new WP_Error('menu_item_deletion_failed', __('Failed to delete the menu item.', 'nietos-ai'));
        }

        return array(
            'success' => true,
            'menu_id' => $menu_id,
            'item_id' => $item_id
        );
    }

    /**
     * Create widget instance
     */
    private function create_widget($args) {
        if (!current_user_can('edit_theme_options')) {
            return new WP_Error('forbidden', __('You do not have permission to manage widgets.', 'nietos-ai'), array('status' => 403));
        }

        $id_base = isset($args['id_base']) ? sanitize_key($args['id_base']) : '';
        if (empty($id_base)) {
            return new WP_Error('missing_id_base', __('Widget id_base is required.', 'nietos-ai'));
        }

        if (!$this->widget_type_exists($id_base)) {
            return new WP_Error('unknown_widget_type', __('The specified widget type is not registered.', 'nietos-ai'));
        }

        $settings = array();
        if (isset($args['settings']) && is_array($args['settings'])) {
            $settings = $this->sanitize_widget_settings($args['settings']);
        }

        $option_name = 'widget_' . $id_base;
        $instances = get_option($option_name, array());
        if (!is_array($instances)) {
            $instances = array();
        }

        $number = $this->get_next_widget_number($instances);
        $instances[$number] = $settings;
        $instances['_multiwidget'] = 1;

        update_option($option_name, $instances);

        $widget_id = $id_base . '-' . $number;
        $assigned_sidebar = null;

        if (!empty($args['sidebar_id'])) {
            $sidebar_id = sanitize_key($args['sidebar_id']);
            $position = isset($args['position']) ? absint($args['position']) : null;
            $assign_result = $this->assign_widget_to_sidebar_internal($widget_id, $sidebar_id, $position);

            if (is_wp_error($assign_result)) {
                // Roll back widget creation if assignment fails
                unset($instances[$number]);
                update_option($option_name, $instances);
                return $assign_result;
            }

            $assigned_sidebar = $sidebar_id;
        }

        return array(
            'success' => true,
            'widget_id' => $widget_id,
            'id_base' => $id_base,
            'sidebar_id' => $assigned_sidebar
        );
    }

    /**
     * Update widget settings
     */
    private function update_widget($args) {
        if (!current_user_can('edit_theme_options')) {
            return new WP_Error('forbidden', __('You do not have permission to manage widgets.', 'nietos-ai'), array('status' => 403));
        }

        $widget_id = isset($args['widget_id']) ? sanitize_text_field($args['widget_id']) : '';
        if (empty($widget_id)) {
            return new WP_Error('missing_widget_id', __('Widget ID is required.', 'nietos-ai'));
        }

        $parsed = $this->parse_widget_id($widget_id);
        if (is_wp_error($parsed)) {
            return $parsed;
        }

        list($id_base, $number) = $parsed;

        if (!$this->widget_type_exists($id_base)) {
            return new WP_Error('unknown_widget_type', __('The specified widget type is not registered.', 'nietos-ai'));
        }

        $option_name = 'widget_' . $id_base;
        $instances = get_option($option_name, array());
        if (!is_array($instances) || !isset($instances[$number])) {
            return new WP_Error('widget_not_found', __('The specified widget instance could not be found.', 'nietos-ai'));
        }

        if (!isset($args['settings']) || !is_array($args['settings'])) {
            return new WP_Error('invalid_settings', __('Widget settings must be provided as an object.', 'nietos-ai'));
        }

        $instances[$number] = $this->sanitize_widget_settings($args['settings']);
        update_option($option_name, $instances);

        return array(
            'success' => true,
            'widget_id' => $widget_id
        );
    }

    /**
     * Delete widget
     */
    private function delete_widget($args) {
        if (!current_user_can('edit_theme_options')) {
            return new WP_Error('forbidden', __('You do not have permission to manage widgets.', 'nietos-ai'), array('status' => 403));
        }

        $widget_id = isset($args['widget_id']) ? sanitize_text_field($args['widget_id']) : '';
        $confirm = isset($args['confirm']) ? (bool) $args['confirm'] : false;

        if (empty($widget_id) || !$confirm) {
            return new WP_Error('confirmation_required', __('Widget ID and confirmation are required.', 'nietos-ai'));
        }

        $parsed = $this->parse_widget_id($widget_id);
        if (is_wp_error($parsed)) {
            return $parsed;
        }

        list($id_base, $number) = $parsed;

        $option_name = 'widget_' . $id_base;
        $instances = get_option($option_name, array());
        if (!is_array($instances) || !isset($instances[$number])) {
            return new WP_Error('widget_not_found', __('The specified widget instance could not be found.', 'nietos-ai'));
        }

        unset($instances[$number]);
        update_option($option_name, $instances);

        $this->remove_widget_from_all_sidebars($widget_id);

        return array(
            'success' => true,
            'widget_id' => $widget_id
        );
    }

    /**
     * Assign widget to sidebar
     */
    private function assign_widget_to_sidebar($args) {
        if (!current_user_can('edit_theme_options')) {
            return new WP_Error('forbidden', __('You do not have permission to manage widgets.', 'nietos-ai'), array('status' => 403));
        }

        $widget_id = isset($args['widget_id']) ? sanitize_text_field($args['widget_id']) : '';
        $sidebar_id = isset($args['sidebar_id']) ? sanitize_key($args['sidebar_id']) : '';
        $position = isset($args['position']) ? absint($args['position']) : null;

        if (empty($widget_id) || empty($sidebar_id)) {
            return new WP_Error('missing_fields', __('Widget ID and sidebar ID are required.', 'nietos-ai'));
        }

        $parsed = $this->parse_widget_id($widget_id);
        if (is_wp_error($parsed)) {
            return $parsed;
        }

        list($id_base, $number) = $parsed;

        $option_name = 'widget_' . $id_base;
        $instances = get_option($option_name, array());
        if (!is_array($instances) || !isset($instances[$number])) {
            return new WP_Error('widget_not_found', __('The specified widget instance could not be found.', 'nietos-ai'));
        }

        $result = $this->assign_widget_to_sidebar_internal($widget_id, $sidebar_id, $position);
        if (is_wp_error($result)) {
            return $result;
        }

        return array(
            'success' => true,
            'widget_id' => $widget_id,
            'sidebar_id' => $sidebar_id
        );
    }

    /**
     * Activate plugin
     */
    private function activate_plugin($args) {
        if (!current_user_can('activate_plugins')) {
            return new WP_Error('forbidden', __('You do not have permission to activate plugins.', 'nietos-ai'), array('status' => 403));
        }

        $plugin = isset($args['plugin']) ? sanitize_text_field($args['plugin']) : '';
        if (empty($plugin)) {
            return new WP_Error('missing_plugin', __('Plugin path is required.', 'nietos-ai'));
        }

        require_once ABSPATH . 'wp-admin/includes/plugin.php';

        $validation = validate_plugin($plugin);
        if (is_wp_error($validation)) {
            return new WP_Error('invalid_plugin', $validation->get_error_message());
        }

        $network_wide = false;
        if (!empty($args['network_wide']) && is_multisite()) {
            if (!current_user_can('manage_network_plugins')) {
                return new WP_Error('forbidden', __('You do not have permission to manage network plugins.', 'nietos-ai'), array('status' => 403));
            }
            $network_wide = true;
        }

        $result = activate_plugin($plugin, '', $network_wide);

        if (is_wp_error($result)) {
            return new WP_Error('plugin_activation_failed', $result->get_error_message());
        }

        return array(
            'success' => true,
            'plugin' => $plugin,
            'active' => true,
            'network_wide' => $network_wide
        );
    }

    /**
     * Deactivate plugin
     */
    private function deactivate_plugin($args) {
        if (!current_user_can('activate_plugins')) {
            return new WP_Error('forbidden', __('You do not have permission to deactivate plugins.', 'nietos-ai'), array('status' => 403));
        }

        $plugin = isset($args['plugin']) ? sanitize_text_field($args['plugin']) : '';
        $confirm = isset($args['confirm']) ? (bool) $args['confirm'] : false;

        if (empty($plugin) || !$confirm) {
            return new WP_Error('confirmation_required', __('Plugin path and confirmation are required.', 'nietos-ai'));
        }

        require_once ABSPATH . 'wp-admin/includes/plugin.php';

        $validation = validate_plugin($plugin);
        if (is_wp_error($validation)) {
            return new WP_Error('invalid_plugin', $validation->get_error_message());
        }

        $network_wide = false;
        if (!empty($args['network_wide']) && is_multisite()) {
            if (!current_user_can('manage_network_plugins')) {
                return new WP_Error('forbidden', __('You do not have permission to manage network plugins.', 'nietos-ai'), array('status' => 403));
            }
            $network_wide = true;
        }

        if (!is_plugin_active($plugin) && !($network_wide && is_plugin_active_for_network($plugin))) {
            return new WP_Error('plugin_not_active', __('The specified plugin is not active.', 'nietos-ai'));
        }

        deactivate_plugins($plugin, false, $network_wide);

        return array(
            'success' => true,
            'plugin' => $plugin,
            'active' => false,
            'network_wide' => $network_wide
        );
    }

    /**
     * Parse widget ID into base and number
     */
    private function parse_widget_id($widget_id) {
        if (strpos($widget_id, '-') === false) {
            return new WP_Error('invalid_widget_id', __('Invalid widget ID format.', 'nietos-ai'));
        }

        $parts = explode('-', $widget_id);
        $number = array_pop($parts);

        if ($number === '' || !ctype_digit((string) $number)) {
            return new WP_Error('invalid_widget_id', __('Invalid widget ID format.', 'nietos-ai'));
        }

        $id_base = implode('-', $parts);
        if (empty($id_base)) {
            return new WP_Error('invalid_widget_id', __('Invalid widget ID format.', 'nietos-ai'));
        }

        return array($id_base, (int) $number);
    }

    /**
     * Check if widget type exists
     */
    private function widget_type_exists($id_base) {
        global $wp_widget_factory;

        if (!isset($wp_widget_factory) || empty($wp_widget_factory->widgets)) {
            return false;
        }

        foreach ($wp_widget_factory->widgets as $widget_obj) {
            if (isset($widget_obj->id_base) && $widget_obj->id_base === $id_base) {
                return true;
            }
        }

        return false;
    }

    /**
     * Sanitize widget settings recursively
     */
    private function sanitize_widget_settings($settings) {
        $sanitized = array();

        foreach ($settings as $key => $value) {
            if (is_array($value)) {
                $sanitized[$key] = $this->sanitize_widget_settings($value);
            } elseif (is_string($value)) {
                $sanitized[$key] = wp_kses_post($value);
            } elseif (is_bool($value) || is_int($value) || is_float($value) || is_null($value)) {
                $sanitized[$key] = $value;
            } else {
                $sanitized[$key] = sanitize_text_field((string) $value);
            }
        }

        return $sanitized;
    }

    /**
     * Get next widget number for id_base
     */
    private function get_next_widget_number($instances) {
        $max = 0;
        foreach ($instances as $key => $_value) {
            if ($key === '_multiwidget') {
                continue;
            }

            if (is_int($key) || ctype_digit((string) $key)) {
                $max = max($max, (int) $key);
            }
        }

        return $max + 1;
    }

    /**
     * Assign widget to sidebar (internal helper)
     */
    private function assign_widget_to_sidebar_internal($widget_id, $sidebar_id, $position = null) {
        if (empty($sidebar_id)) {
            return new WP_Error('invalid_sidebar', __('Sidebar ID is required.', 'nietos-ai'));
        }

        if (!$this->is_registered_sidebar($sidebar_id) && 'wp_inactive_widgets' !== $sidebar_id) {
            return new WP_Error('invalid_sidebar', __('The specified sidebar is not registered.', 'nietos-ai'));
        }

        $sidebars = wp_get_sidebars_widgets();
        if (!is_array($sidebars)) {
            $sidebars = array();
        }

        $sidebars = $this->remove_widget_from_sidebars_array($sidebars, $widget_id);

        if (!isset($sidebars[$sidebar_id]) || !is_array($sidebars[$sidebar_id])) {
            $sidebars[$sidebar_id] = array();
        }

        if ($position !== null && $position >= 0 && $position <= count($sidebars[$sidebar_id])) {
            array_splice($sidebars[$sidebar_id], $position, 0, array($widget_id));
        } else {
            $sidebars[$sidebar_id][] = $widget_id;
        }

        wp_set_sidebars_widgets($sidebars);

        return true;
    }

    /**
     * Remove widget from all sidebars
     */
    private function remove_widget_from_all_sidebars($widget_id) {
        $sidebars = wp_get_sidebars_widgets();
        if (!is_array($sidebars)) {
            return;
        }

        $updated = $this->remove_widget_from_sidebars_array($sidebars, $widget_id);
        wp_set_sidebars_widgets($updated);
    }

    /**
     * Remove widget from sidebar array helper
     */
    private function remove_widget_from_sidebars_array($sidebars, $widget_id) {
        foreach ($sidebars as $sidebar => $widgets) {
            if (!is_array($widgets)) {
                continue;
            }

            $sidebars[$sidebar] = array_values(array_filter($widgets, function ($existing) use ($widget_id) {
                return $existing !== $widget_id;
            }));
        }

        return $sidebars;
    }

    /**
     * Check if sidebar is registered
     */
    private function is_registered_sidebar($sidebar_id) {
        global $wp_registered_sidebars;

        return isset($wp_registered_sidebars[$sidebar_id]);
    }
}
