<?php
/**
 * AI Agent Tools Base Class and Tool Definitions
 * 
 * @package AI_Auto_Tool
 */

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

/**
 * Base class for AI Agent Tools
 */
abstract class AIAutotool_Agent_Tool {
    
    /**
     * Tool name
     * @var string
     */
    protected $name = '';
    
    /**
     * Tool description
     * @var string
     */
    protected $description = '';
    
    /**
     * Tool parameters schema
     * @var array
     */
    protected $parameters = array();
    
    /**
     * Get tool name
     * 
     * @return string
     */
    public function get_name() {
        return $this->name;
    }
    
    /**
     * Get tool description
     * 
     * @return string
     */
    public function get_description() {
        return $this->description;
    }
    
    /**
     * Get tool parameters
     * 
     * @return array
     */
    public function get_parameters() {
        return $this->parameters;
    }
    
    /**
     * Get tool metadata
     * 
     * @return array
     */
    public function get_metadata() {
        return array(
            'name' => $this->name,
            'description' => $this->description,
            'parameters' => $this->parameters
        );
    }
    
    /**
     * Validate parameters
     * 
     * @param array $params Parameters to validate
     * @return array Validation result with 'valid' and 'errors' keys
     */
    public function validate_parameters($params) {
        $errors = array();
        
        foreach ($this->parameters as $param_name => $param_config) {
            $is_required = isset($param_config['required']) && $param_config['required'];
            
            if ($is_required && !isset($params[$param_name])) {
                $errors[] = "Missing required parameter: {$param_name}";
            }
        }
        
        return array(
            'valid' => empty($errors),
            'errors' => $errors
        );
    }
    
    /**
     * Execute the tool
     * 
     * @param array $params Tool parameters
     * @param AIAutoTool_SSE_Stream|null $stream Optional SSE stream for progress updates
     * @return array Execution result with 'success', 'data', and optional 'error' keys
     */
    abstract public function execute($params, $stream = null);
}

/**
 * Write Post Tool
 * Generates post content using AI
 */
class AIAutotool_Write_Post_Tool extends AIAutotool_Agent_Tool {
    
    protected $name = 'write_post';
    protected $description = 'Generate post content using AI based on title and requirements';
    protected $parameters = array(
        'title' => array(
            'type' => 'string',
            'description' => 'Post title',
            'required' => false  // Made optional since we can use topic
        ),
        'topic' => array(
            'type' => 'string',
            'description' => 'Post topic (will be used as title if title not provided)',
            'required' => false
        ),
        'language' => array(
            'type' => 'string',
            'description' => 'Content language (e.g., Vietnamese, English)',
            'required' => false,
            'default' => 'Vietnamese'
        ),
        'length' => array(
            'type' => 'string',
            'description' => 'Content length (short, medium, long)',
            'required' => false,
            'default' => 'medium'
        ),
        'tone' => array(
            'type' => 'string',
            'description' => 'Content tone (professional, casual, friendly)',
            'required' => false,
            'default' => 'professional'
        ),
        'outline_context' => array(
            'type' => 'string',
            'description' => 'Additional context for outline/content structure',
            'required' => false
        ),
        'structure_guidance' => array(
            'type' => 'string',
            'description' => 'Guidance for content structure/outline',
            'required' => false
        ),
        'keywords' => array(
            'type' => 'array',
            'description' => 'SEO keywords to include in content',
            'required' => false
        )
    );
    
    public function execute($params, $stream = null) {
        // Map topic to title if title not provided
        if (empty($params['title']) && !empty($params['topic'])) {
            $params['title'] = $params['topic'];
        }
        
        // Map structure_guidance to outline_context if needed
        if (empty($params['outline_context']) && !empty($params['structure_guidance'])) {
            $params['outline_context'] = $params['structure_guidance'];
        }
        
        // Ensure title exists
        if (empty($params['title'])) {
            return array(
                'success' => false,
                'error' => 'Missing required parameter: title or topic'
            );
        }
        
        // Validate parameters (skip strict validation for title since we handled it)
        $validation = $this->validate_parameters($params);
        if (!$validation['valid']) {
            // Don't fail on title validation if we have topic
            $errors = array_filter($validation['errors'], function($error) {
                return strpos($error, 'title') === false;
            });
            if (!empty($errors)) {
                return array(
                    'success' => false,
                    'error' => implode(', ', $errors)
                );
            }
        }
        
        $title = $params['title'];
        $language = isset($params['language']) ? $params['language'] : 'Vietnamese';
        $length = isset($params['length']) ? $params['length'] : 'medium';
        $tone = isset($params['tone']) ? $params['tone'] : 'professional';
        
        // Support additional params from plan
        $outline_context = isset($params['outline_context']) ? $params['outline_context'] : '';
        $keywords = isset($params['keywords']) && is_array($params['keywords']) ? $params['keywords'] : array();
        
        if ($stream) {
            $stream->send_status("Starting AI Auto Writer for: {$title}");
        }
        
        // Load AI Auto Writer
        require_once plugin_dir_path(__FILE__) . 'aiautotool_ai_auto_writer.php';
        
        // Map language from Vietnamese/English to vi/en
        $lang_code = 'vi';
        if (stripos($language, 'english') !== false || stripos($language, 'en') !== false) {
            $lang_code = 'en';
        }
        
        // Map length to detailed_level and sections
        $detailed_level = 'high';
        $min_sections = 5;
        $max_sections = 10;
        
        if ($length === 'short') {
            $detailed_level = 'medium';
            $min_sections = 3;
            $max_sections = 5;
        } elseif ($length === 'medium') {
            $detailed_level = 'medium';
            $min_sections = 5;
            $max_sections = 7;
        } else {
            // long
            $detailed_level = 'high';
            $min_sections = 7;
            $max_sections = 10;
        }
        
        // Prepare options for auto writer
        $options = array(
            'language' => $lang_code,
            'min_sections' => $min_sections,
            'max_sections' => $max_sections,
            'detailed_level' => $detailed_level,
            'debug' => false,
        );
        
        // Add outline context if provided
        if (!empty($outline_context)) {
            $options['custom_prompt'] = $outline_context;
        }
        
        // Get auto writer instance
        $writer = aiautotool_ai_auto_writer();
        
        try {
            // Send progress updates via stream
            if ($stream) {
                $stream->send_status("Analyzing title and creating outline...");
            }
            
            // Execute auto writer
            $result = $writer->write_article_from_title($title, $options);
            
            if (!$result['success']) {
                $error = isset($result['error']) ? $result['error'] : 'Failed to generate content';
                if ($stream) {
                    $stream->send_error($error);
                }
                return array(
                    'success' => false,
                    'error' => $error
                );
            }
            
            $content = $result['full_content'];
            $word_count = $result['word_count'];
            
            if ($stream) {
                $stream->send_status("Article generated successfully - {$word_count} words, " . strlen($content) . " characters");
            }
            
            // Get provider/model info from agent
            $agent = AIAutotool_AI_Agent::get_instance();
            $combinations = $agent->get_preferred_combinations('long_context');
            $model = isset($combinations[0]['model']) ? $combinations[0]['model'] : 'gemini';
            $provider = isset($combinations[0]['provider']) ? $combinations[0]['provider'] : 'gemini';
            
            return array(
                'success' => true,
                'content' => $content,  // Return content directly for executor
                'data' => array(
                    'title' => $title,
                    'content' => $content,
                    'word_count' => $word_count,
                    'provider' => $provider,
                    'model' => $model,
                    'outline' => isset($result['outline']) ? $result['outline'] : array(),
                    'sections' => isset($result['sections']) ? $result['sections'] : array(),
                    'execution_time' => isset($result['execution_time']) ? $result['execution_time'] : 0
                )
            );
        } catch (Exception $e) {
            $error_message = $e->getMessage();
            if ($stream) {
                $stream->send_error($error_message);
            }
            return array(
                'success' => false,
                'error' => $error_message
            );
        }
    }
}

/**
 * Create Image Tool
 * Generates images using AI
 */
class AIAutotool_Create_Image_Tool extends AIAutotool_Agent_Tool {
    
    protected $name = 'create_image';
    protected $description = 'Generate an image using AI based on description';
    protected $parameters = array(
        'prompt' => array(
            'type' => 'string',
            'description' => 'Image description/prompt',
            'required' => true
        ),
        'title' => array(
            'type' => 'string',
            'description' => 'Image title/alt text',
            'required' => false
        )
    );
    
    public function execute($params, $stream = null) {
        // Validate parameters
        $validation = $this->validate_parameters($params);
        if (!$validation['valid']) {
            return array(
                'success' => false,
                'error' => implode(', ', $validation['errors'])
            );
        }
        
        $prompt = $params['prompt'];
        $title = isset($params['title']) ? $params['title'] : $prompt;
        
        if ($stream) {
            $stream->send_status("Generating image: {$prompt}");
        }
        
        // Check if image generator is available
        if (!class_exists('BardGenContent')) {
            $bard_file = plugin_dir_path(dirname(dirname(dirname(__FILE__)))) . 'lib/bard.php';
            if (file_exists($bard_file)) {
                require_once $bard_file;
            }
        }
        
        if (!class_exists('BardGenContent')) {
            return array(
                'success' => false,
                'error' => 'Image generation API not available'
            );
        }
        
        try {
            $bard = new BardGenContent();
            
            // Generate image
            $image_result = $bard->generateImage($prompt);
            
            if (!$image_result || !isset($image_result['url'])) {
                return array(
                    'success' => false,
                    'error' => 'Failed to generate image'
                );
            }
            
            if ($stream) {
                $stream->send_status("Image generated successfully");
            }
            
            return array(
                'success' => true,
                'data' => array(
                    'url' => $image_result['url'],
                    'prompt' => $prompt,
                    'title' => $title,
                    'alt' => $title
                )
            );
            
        } catch (Exception $e) {
            return array(
                'success' => false,
                'error' => 'Image generation error: ' . $e->getMessage()
            );
        }
    }
}

/**
 * WordPress Post Management Tool
 * Creates/updates WordPress posts with metadata
 */
class AIAutotool_WordPress_Post_Tool extends AIAutotool_Agent_Tool {
    
    protected $name = 'wordpress_post';
    protected $description = 'Create or update WordPress post with content and metadata';
    protected $parameters = array(
        'title' => array(
            'type' => 'string',
            'description' => 'Post title',
            'required' => true
        ),
        'content' => array(
            'type' => 'string',
            'description' => 'Post content (HTML)',
            'required' => true
        ),
        'post_id' => array(
            'type' => 'integer',
            'description' => 'Existing post ID to update (optional)',
            'required' => false
        ),
        'status' => array(
            'type' => 'string',
            'description' => 'Post status (draft, publish, pending)',
            'required' => false,
            'default' => 'draft'
        ),
        'categories' => array(
            'type' => 'array',
            'description' => 'Category names or IDs',
            'required' => false
        ),
        'tags' => array(
            'type' => 'array',
            'description' => 'Tag names',
            'required' => false
        ),
        'thumbnail_url' => array(
            'type' => 'string',
            'description' => 'Featured image URL',
            'required' => false
        ),
        'excerpt' => array(
            'type' => 'string',
            'description' => 'Post excerpt',
            'required' => false
        )
    );
    
    public function execute($params, $stream = null) {
        // Validate parameters
        $validation = $this->validate_parameters($params);
        if (!$validation['valid']) {
            return array(
                'success' => false,
                'error' => implode(', ', $validation['errors'])
            );
        }
        
        $title = $params['title'];
        $content = $params['content'];
        $post_id = isset($params['post_id']) ? intval($params['post_id']) : 0;
        $status = isset($params['status']) ? $params['status'] : 'draft';
        
        if ($stream) {
            $action = $post_id > 0 ? 'Updating' : 'Creating';
            $stream->send_status("{$action} WordPress post: {$title}");
        }
        
        // Prepare post data
        $post_data = array(
            'post_title' => $title,
            'post_content' => $content,
            'post_status' => $status,
            'post_type' => 'post'
        );
        
        if (isset($params['excerpt'])) {
            $post_data['post_excerpt'] = $params['excerpt'];
        }
        
        // Create or update post
        if ($post_id > 0) {
            $post_data['ID'] = $post_id;
            $result_id = wp_update_post($post_data, true);
        } else {
            $result_id = wp_insert_post($post_data, true);
        }
        
        if (is_wp_error($result_id)) {
            return array(
                'success' => false,
                'error' => $result_id->get_error_message()
            );
        }
        
        $post_id = $result_id;
        
        // Add categories
        if (isset($params['categories']) && is_array($params['categories']) && !empty($params['categories'])) {
            $category_ids = array();
            foreach ($params['categories'] as $cat) {
                if (is_numeric($cat)) {
                    $category_ids[] = intval($cat);
                } else {
                    // Get or create category by name
                    $term = term_exists($cat, 'category');
                    if (!$term) {
                        $term = wp_insert_term($cat, 'category');
                    }
                    if (!is_wp_error($term) && isset($term['term_id'])) {
                        $category_ids[] = $term['term_id'];
                    }
                }
            }
            if (!empty($category_ids)) {
                wp_set_post_categories($post_id, $category_ids);
                if ($stream) {
                    $stream->send_status("Added " . count($category_ids) . " categories");
                }
            }
        }
        
        // Add tags
        if (isset($params['tags']) && is_array($params['tags']) && !empty($params['tags'])) {
            wp_set_post_tags($post_id, $params['tags'], false);
            if ($stream) {
                $stream->send_status("Added " . count($params['tags']) . " tags");
            }
        }
        
        // Add featured image from URL
        if (isset($params['thumbnail_url']) && !empty($params['thumbnail_url'])) {
            $thumbnail_result = $this->set_featured_image_from_url($post_id, $params['thumbnail_url'], $title, $stream);
            if (!$thumbnail_result['success'] && $stream) {
                $stream->send_status("Warning: " . $thumbnail_result['error']);
            }
        }
        
        if ($stream) {
            $stream->send_status("Post " . ($post_id > 0 ? 'updated' : 'created') . " successfully (ID: {$result_id})");
        }
        
        return array(
            'success' => true,
            'data' => array(
                'post_id' => $result_id,
                'post_url' => get_permalink($result_id),
                'edit_url' => admin_url('post.php?post=' . $result_id . '&action=edit'),
                'status' => $status
            )
        );
    }
    
    /**
     * Set featured image from URL
     * 
     * @param int $post_id Post ID
     * @param string $image_url Image URL
     * @param string $title Image title
     * @param AIAutoTool_SSE_Stream|null $stream SSE stream
     * @return array Result
     */
    private function set_featured_image_from_url($post_id, $image_url, $title, $stream = null) {
        if ($stream) {
            $stream->send_status("Downloading featured image...");
        }
        
        // Download image
        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 = download_url($image_url);
        
        if (is_wp_error($tmp)) {
            return array(
                'success' => false,
                'error' => 'Failed to download image: ' . $tmp->get_error_message()
            );
        }
        
        // Prepare file array
        $file_array = array(
            'name' => basename($image_url),
            'tmp_name' => $tmp
        );
        
        // Upload to media library
        $attachment_id = media_handle_sideload($file_array, $post_id, $title);
        
        // Clean up temp file
        @unlink($tmp);
        
        if (is_wp_error($attachment_id)) {
            return array(
                'success' => false,
                'error' => 'Failed to upload image: ' . $attachment_id->get_error_message()
            );
        }
        
        // Set as featured image
        set_post_thumbnail($post_id, $attachment_id);
        
        if ($stream) {
            $stream->send_status("Featured image set successfully");
        }
        
        return array(
            'success' => true,
            'data' => array(
                'attachment_id' => $attachment_id
            )
        );
    }
}

/**
 * Get Post Tool
 * Retrieve full details of a specific post
 */
class AIAutotool_Get_Post_Tool extends AIAutotool_Agent_Tool {
    
    protected $name = 'get_post';
    protected $description = 'Get full details of a specific post by ID';
    protected $parameters = array(
        'post_id' => array(
            'type' => 'integer',
            'description' => 'Post ID',
            'required' => true
        )
    );
    
    public function execute($params, $stream = null) {
        $validation = $this->validate_parameters($params);
        if (!$validation['valid']) {
            return array('success' => false, 'error' => implode(', ', $validation['errors']));
        }
        
        $post_id = intval($params['post_id']);
        $post = get_post($post_id);
        
        if (!$post) {
            return array('success' => false, 'error' => 'Post not found');
        }
        
        // Get categories and tags
        $categories = get_the_category($post_id);
        $tags = get_the_tags($post_id);
        
        $cats_list = array();
        if ($categories) {
            foreach ($categories as $cat) {
                $cats_list[] = $cat->name;
            }
        }
        
        $tags_list = array();
        if ($tags) {
            foreach ($tags as $tag) {
                $tags_list[] = $tag->name;
            }
        }
        
        if ($stream) {
            $stream->send_status("Retrieved post: {$post->post_title}");
        }
        
        return array(
            'success' => true,
            'data' => array(
                'id' => $post->ID,
                'title' => $post->post_title,
                'content' => $post->post_content,
                'excerpt' => $post->post_excerpt,
                'status' => $post->post_status,
                'date' => $post->post_date,
                'author' => get_the_author_meta('display_name', $post->post_author),
                'url' => get_permalink($post->ID),
                'categories' => $cats_list,
                'tags' => $tags_list
            )
        );
    }
}

/**
 * Search Posts Tool
 * Find posts using WP_Query
 */
class AIAutotool_Search_Posts_Tool extends AIAutotool_Agent_Tool {
    
    protected $name = 'search_posts';
    protected $description = 'Search for posts using keywords and filters';
    protected $parameters = array(
        'keyword' => array(
            'type' => 'string',
            'description' => 'Search keyword',
            'required' => true
        ),
        'post_type' => array(
            'type' => 'string',
            'description' => 'Post type (post, page)',
            'required' => false,
            'default' => 'post'
        ),
        'post_status' => array(
            'type' => 'string',
            'description' => 'Post status (publish, draft, any)',
            'required' => false,
            'default' => 'publish'
        ),
        'limit' => array(
            'type' => 'integer',
            'description' => 'Max number of results',
            'required' => false,
            'default' => 5
        ),
        'category' => array(
            'type' => 'string',
            'description' => 'Category slug to filter by',
            'required' => false
        )
    );
    
    public function execute($params, $stream = null) {
        $validation = $this->validate_parameters($params);
        if (!$validation['valid']) {
            return array('success' => false, 'error' => implode(', ', $validation['errors']));
        }
        
        $args = array(
            's' => $params['keyword'],
            'post_type' => isset($params['post_type']) ? $params['post_type'] : 'post',
            'post_status' => isset($params['post_status']) ? $params['post_status'] : 'publish',
            'posts_per_page' => isset($params['limit']) ? intval($params['limit']) : 5,
        );
        
        if (isset($params['category']) && !empty($params['category'])) {
            $args['category_name'] = $params['category'];
        }
        
        if ($stream) {
            $stream->send_status("Searching posts for: {$params['keyword']}");
        }
        
        $query = new WP_Query($args);
        $posts = $query->posts;
        
        $results = array();
        foreach ($posts as $post) {
            $results[] = array(
                'id' => $post->ID,
                'title' => $post->post_title,
                'status' => $post->post_status,
                'date' => $post->post_date,
                'url' => get_permalink($post->ID)
            );
        }
        
        return array(
            'success' => true,
            'data' => array(
                'count' => count($results),
                'posts' => $results
            )
        );
    }
}

/**
 * List Terms Tool
 * List categories or tags
 */
class AIAutotool_List_Terms_Tool extends AIAutotool_Agent_Tool {
    
    protected $name = 'list_terms';
    protected $description = 'List categories, tags or other taxonomies';
    protected $parameters = array(
        'taxonomy' => array(
            'type' => 'string',
            'description' => 'Taxonomy name (category, post_tag)',
            'required' => false,
            'default' => 'category'
        ),
        'hide_empty' => array(
            'type' => 'boolean',
            'description' => 'Hide empty terms',
            'required' => false,
            'default' => true
        )
    );
    
    public function execute($params, $stream = null) {
        $taxonomy = isset($params['taxonomy']) ? $params['taxonomy'] : 'category';
        $hide_empty = isset($params['hide_empty']) ? $params['hide_empty'] : true;
        
        $terms = get_terms(array(
            'taxonomy' => $taxonomy,
            'hide_empty' => $hide_empty
        ));
        
        if (is_wp_error($terms)) {
            return array('success' => false, 'error' => $terms->get_error_message());
        }
        
        $results = array();
        foreach ($terms as $term) {
            $results[] = array(
                'id' => $term->term_id,
                'name' => $term->name,
                'slug' => $term->slug,
                'count' => $term->count
            );
        }
        
        return array(
            'success' => true,
            'data' => $results
        );
    }
}

/**
 * Get Comments Tool
 * Retrieve recent comments
 */
class AIAutotool_Get_Comments_Tool extends AIAutotool_Agent_Tool {
    
    protected $name = 'get_comments';
    protected $description = 'Get recent comments';
    protected $parameters = array(
        'post_id' => array(
            'type' => 'integer',
            'description' => 'Filter by Post ID',
            'required' => false
        ),
        'status' => array(
            'type' => 'string',
            'description' => 'Comment status (approve, hold, spam, trash)',
            'required' => false,
            'default' => 'approve'
        ),
        'limit' => array(
            'type' => 'integer',
            'description' => 'Max number of comments',
            'required' => false,
            'default' => 10
        )
    );
    
    public function execute($params, $stream = null) {
        $args = array(
            'status' => isset($params['status']) ? $params['status'] : 'approve',
            'number' => isset($params['limit']) ? intval($params['limit']) : 10,
        );
        
        if (isset($params['post_id']) && !empty($params['post_id'])) {
            $args['post_id'] = intval($params['post_id']);
        }
        
        if ($stream) {
            $status_msg = "Getting comments";
            if (isset($args['post_id'])) $status_msg .= " for post {$args['post_id']}";
            $stream->send_status($status_msg);
        }
        
        $comments = get_comments($args);
        
        $results = array();
        foreach ($comments as $comment) {
            $results[] = array(
                'id' => $comment->comment_ID,
                'post_id' => $comment->comment_post_ID,
                'author' => $comment->comment_author,
                'content' => $comment->comment_content,
                'date' => $comment->comment_date,
                'status' => wp_get_comment_status($comment->comment_ID)
            );
        }
        
        return array(
            'success' => true,
            'data' => $results
        );
    }
}

/**
 * Reply Comment Tool
 * Reply to a comment
 */
class AIAutotool_Reply_Comment_Tool extends AIAutotool_Agent_Tool {
    
    protected $name = 'reply_comment';
    protected $description = 'Reply to a comment';
    protected $parameters = array(
        'comment_id' => array(
            'type' => 'integer',
            'description' => 'ID of the comment to reply to',
            'required' => true
        ),
        'content' => array(
            'type' => 'string',
            'description' => 'Reply content',
            'required' => true
        )
    );
    
    public function execute($params, $stream = null) {
        $validation = $this->validate_parameters($params);
        if (!$validation['valid']) {
            return array('success' => false, 'error' => implode(', ', $validation['errors']));
        }
        
        $parent_id = intval($params['comment_id']);
        $content = $params['content'];
        $parent_comment = get_comment($parent_id);
        
        if (!$parent_comment) {
            return array('success' => false, 'error' => 'Parent comment not found');
        }
        
        if ($stream) {
            $stream->send_status("Replying to comment {$parent_id}");
        }
        
        $user = wp_get_current_user();
        
        $comment_data = array(
            'comment_post_ID' => $parent_comment->comment_post_ID,
            'comment_author' => $user->exists() ? $user->display_name : 'AI Agent',
            'comment_author_email' => $user->exists() ? $user->user_email : '',
            'comment_content' => $content,
            'comment_type' => 'comment',
            'comment_parent' => $parent_id,
            'user_id' => $user->exists() ? $user->ID : 0,
            'comment_approved' => 1
        );
        
        $comment_id = wp_insert_comment($comment_data);
        
        if (!$comment_id) {
            return array('success' => false, 'error' => 'Failed to insert comment');
        }
        
        return array(
            'success' => true,
            'data' => array(
                'comment_id' => $comment_id,
                'post_id' => $parent_comment->comment_post_ID,
                'parent' => $parent_id,
                'content' => $content
            )
        );
    }
}

/**
 * Tool Manager
 * Manages all available tools
 */
class AIAutotool_Agent_Tool_Manager {
    
    private static $instance = null;
    private $tools = array();
    
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        $this->register_default_tools();
    }
    
    /**
     * Register default tools
     */
    private function register_default_tools() {
        $this->register_tool(new AIAutotool_Write_Post_Tool());
        $this->register_tool(new AIAutotool_Create_Image_Tool());
        $this->register_tool(new AIAutotool_WordPress_Post_Tool());
        $this->register_tool(new AIAutotool_Get_Post_Tool());
        $this->register_tool(new AIAutotool_Search_Posts_Tool());
        $this->register_tool(new AIAutotool_List_Terms_Tool());
        $this->register_tool(new AIAutotool_Get_Comments_Tool());
        $this->register_tool(new AIAutotool_Reply_Comment_Tool());
    }
    
    /**
     * Register a tool
     * 
     * @param AIAutotool_Agent_Tool $tool Tool instance
     */
    public function register_tool($tool) {
        $this->tools[$tool->get_name()] = $tool;
    }
    
    /**
     * Get a tool by name
     * 
     * @param string $name Tool name
     * @return AIAutotool_Agent_Tool|null
     */
    public function get_tool($name) {
        return isset($this->tools[$name]) ? $this->tools[$name] : null;
    }
    
    /**
     * Get all tools
     * 
     * @return array Array of tools
     */
    public function get_all_tools() {
        return $this->tools;
    }
    
    /**
     * Get tools metadata
     * 
     * @return array Array of tool metadata
     */
    public function get_tools_metadata() {
        $metadata = array();
        foreach ($this->tools as $name => $tool) {
            $metadata[$name] = $tool->get_metadata();
        }
        return $metadata;
    }
}
