<?php
/**
 * AI Agent Planner
 * Handles planning phase: analyzes requests, creates execution plans, breaks down tasks
 * 
 * @package AI_Auto_Tool
 */

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

/**
 * Agent Planner Class
 * Analyzes requests and creates detailed execution plans following Cursor AI pattern
 */
class AIAutotool_Agent_Planner {
    
    /**
     * AI Provider Manager
     * @var object
     */
    private $manager;
    
    /**
     * Agent context
     * @var AIAutotool_Agent_Context
     */
    private $context;
    
    /**
     * Planning models (prefer reasoning models)
     * @var array
     */
    private $planning_models = array(
        array('provider' => 'openai', 'model' => 'gpt-4o'),
        array('provider' => 'gemini', 'model' => 'gemini-2.5-pro'),
        array('provider' => 'gemini', 'model' => 'gemini-2.5-flash'),
    );
    
    /**
     * Constructor
     * 
     * @param object $manager Provider manager
     * @param AIAutotool_Agent_Context $context Agent context
     */
    public function __construct($manager, $context) {
        $this->manager = $manager;
        $this->context = $context;
    }
    
    /**
     * Analyze request and determine complexity
     * 
     * @param string $request User request
     * @param array $options Options
     * @return array Analysis result
     */
    public function analyze_request($request, $options = array()) {
        $this->context->add_task('analyze_request', 'planning');
        
        $prompt = $this->build_analysis_prompt($request);
        
        // Use reasoning model for analysis
        $result = $this->execute_with_planning_model($prompt, array(
            'temperature' => 0.3, // Lower temperature for analysis
            'task' => 'analyze_request'
        ));
        
        if (!$result['success']) {
            $this->context->add_error('analysis_failed', $result['error']);
            return array(
                'success' => false,
                'error' => $result['error']
            );
        }
        
        // Parse analysis
        $analysis = $this->parse_analysis($result['content']);
        
        $this->context->update_task_status('completed', array('analysis' => $analysis));
        
        return array(
            'success' => true,
            'analysis' => $analysis,
            'raw_response' => $result['content']
        );
    }
    
    /**
     * Build analysis prompt
     * 
     * @param string $request User request
     * @return string
     */
    private function build_analysis_prompt($request) {
        return "Bạn là AI Planning Agent. Phân tích yêu cầu sau và trả về JSON format:

YÊU CẦU: {$request}

Phân tích theo cấu trúc sau (trả về ONLY JSON, không có text khác):
{
    \"complexity\": \"simple|medium|complex\",
    \"use_case\": \"search|reasoning|code|long_context|fast|general\",
    \"requires_tools\": true/false,
    \"tools_needed\": [\"tool1\", \"tool2\"],
    \"estimated_steps\": 3,
    \"needs_clarification\": true/false,
    \"clarification_questions\": [\"question1\", \"question2\"],
    \"suggested_approach\": \"Brief description of approach\"
}

Complexity levels:
- simple: Câu hỏi đơn giản, 1-2 bước
- medium: Cần 3-5 bước, có thể cần tools
- complex: Nhiều bước, cần nhiều tools, cần planning chi tiết

QUAN TRỌNG VỀ CLARIFICATION:
- Đặt \"needs_clarification\": false cho các yêu cầu RÕ RÀNG như:
  * \"viết bài về X\", \"tạo nội dung về Y\", \"write article about Z\"
  * Có topic cụ thể, có action verb rõ ràng (viết, tạo, write, create)
  * Có đủ thông tin để thực hiện task
- Chỉ đặt \"needs_clarification\": true khi:
  * Yêu cầu mơ hồ, thiếu thông tin quan trọng
  * Có nhiều cách hiểu khác nhau
  * Cần thông tin bổ sung để quyết định approach

Cursor-style: Make reasonable assumptions và proceed cho các task rõ ràng!

QUAN TRỌNG: Chỉ trả về JSON, không có markdown, không có explanation.";
    }
    
    /**
     * Parse analysis response
     * 
     * @param string $content Response content
     * @return array
     */
    private function parse_analysis($content) {
        // Remove markdown code blocks if present
        $content = preg_replace('/```json\s*|\s*```/', '', $content);
        $content = trim($content);
        
        $parsed = json_decode($content, true);
        
        if (!$parsed) {
            // Fallback: treat as simple request
            return array(
                'complexity' => 'simple',
                'use_case' => 'general',
                'requires_tools' => false,
                'tools_needed' => array(),
                'estimated_steps' => 1,
                'needs_clarification' => false,
                'clarification_questions' => array(),
                'suggested_approach' => 'Direct response'
            );
        }
        
        return $parsed;
    }
    
    /**
     * Create execution plan
     * 
     * @param array $analysis Analysis result
     * @param string $request Original request
     * @return array Execution plan
     */
    public function create_plan($analysis, $request) {
        $this->context->add_task('create_plan', 'planning');
        
        if ($analysis['complexity'] === 'simple') {
            // Simple request, no detailed planning needed
            return array(
                'success' => true,
                'plan' => array(
                    'steps' => array(
                        array(
                            'step' => 1,
                            'action' => 'execute',
                            'description' => 'Generate response directly',
                            'use_case' => $analysis['use_case'],
                            'requires_tools' => false
                        )
                    ),
                    'complexity' => 'simple',
                    'total_steps' => 1
                )
            );
        }
        
        // Complex request, need detailed planning
        $prompt = $this->build_planning_prompt($analysis, $request);
        
        $result = $this->execute_with_planning_model($prompt, array(
            'temperature' => 0.3,
            'task' => 'create_plan'
        ));
        
        if (!$result['success']) {
            $this->context->add_error('planning_failed', $result['error']);
            return array(
                'success' => false,
                'error' => $result['error']
            );
        }
        
        $plan = $this->parse_plan($result['content']);
        
        $this->context->update_task_status('completed', array('plan' => $plan));
        
        return array(
            'success' => true,
            'plan' => $plan,
            'raw_response' => $result['content']
        );
    }
    
    /**
     * Build planning prompt
     * 
     * @param array $analysis Analysis result
     * @param string $request Original request
     * @return string
     */
    private function build_planning_prompt($analysis, $request) {
        $tools_list = $this->get_available_tools_description();
        
        return "Bạn là AI Planning Agent. Tạo execution plan chi tiết cho yêu cầu sau:

YÊU CẦU: {$request}

PHÂN TÍCH:
- Complexity: {$analysis['complexity']}
- Use case: {$analysis['use_case']}
- Estimated steps: {$analysis['estimated_steps']}
- Suggested approach: {$analysis['suggested_approach']}

TOOLS AVAILABLE:
{$tools_list}

Tạo execution plan theo format JSON (chỉ trả về JSON, không có text khác):
{
    \"steps\": [
        {
            \"step\": 1,
            \"action\": \"tool_call|generate|analyze\",
            \"description\": \"What to do in this step\",
            \"tool_name\": \"tool name if action is tool_call\",
            \"tool_params\": {\"param1\": \"value1\"},
            \"use_case\": \"search|reasoning|code|etc\",
            \"requires_tools\": true/false,
            \"dependencies\": [\"list of step numbers this depends on\"]
        }
    ],
    \"complexity\": \"{$analysis['complexity']}\",
    \"total_steps\": 3,
    \"estimated_time\": \"short|medium|long\",
    \"parallel_execution_possible\": true/false
}

Actions:
- tool_call: Gọi một tool cụ thể
- generate: Generate content bằng AI
- analyze: Phân tích kết quả từ bước trước

QUAN TRỌNG: Chỉ trả về JSON, không có markdown, không có explanation.";
    }
    
    /**
     * Get available tools description
     * 
     * @return string
     */
    private function get_available_tools_description() {
        // Get registered tools from tools class
        if (!class_exists('AIAutotool_Agent_Tool')) {
            return '- write_post: Generate post content\n- create_image: Generate images\n- wordpress_post: Create/update WordPress posts';
        }
        
        // Simplified for now
        return "- write_post: Generate comprehensive post content with AI
- create_image: Generate images using AI
- wordpress_post: Create or update WordPress posts with full metadata
- get_post: Retrieve post details by ID
- search_posts: Search for posts using keywords
- list_terms: List categories or tags
- get_comments: Get recent comments
- reply_comment: Reply to a comment";
    }
    
    /**
     * Parse plan response
     * 
     * @param string $content Response content
     * @return array
     */
    private function parse_plan($content) {
        // Remove markdown code blocks
        $content = preg_replace('/```json\s*|\s*```/', '', $content);
        $content = trim($content);
        
        $plan = json_decode($content, true);
        
        if (!$plan) {
            // Fallback plan
            return array(
                'steps' => array(
                    array(
                        'step' => 1,
                        'action' => 'generate',
                        'description' => 'Execute request',
                        'use_case' => 'general',
                        'requires_tools' => false
                    )
                ),
                'complexity' => 'medium',
                'total_steps' => 1,
                'estimated_time' => 'medium'
            );
        }
        
        return $plan;
    }
    
    /**
     * Check if plan needs user clarification
     * 
     * @param array $analysis Analysis result
     * @return array|null Clarification questions or null
     */
    public function check_clarification_needed($analysis) {
        if (empty($analysis['needs_clarification']) || empty($analysis['clarification_questions'])) {
            return null;
        }
        
        return array(
            'needed' => true,
            'questions' => $analysis['clarification_questions']
        );
    }
    
    /**
     * Break down complex task into sub-tasks
     * 
     * @param array $plan Execution plan
     * @return array Sub-tasks
     */
    public function break_down_tasks($plan) {
        if (empty($plan['steps'])) {
            return array();
        }
        
        $sub_tasks = array();
        
        foreach ($plan['steps'] as $step) {
            $sub_tasks[] = array(
                'id' => 'task_' . $step['step'],
                'step_number' => $step['step'],
                'action' => $step['action'],
                'description' => $step['description'],
                'status' => 'pending',
                'dependencies' => $step['dependencies'] ?? array(),
                'metadata' => array(
                    'use_case' => $step['use_case'] ?? 'general',
                    'requires_tools' => $step['requires_tools'] ?? false,
                    'tool_name' => $step['tool_name'] ?? null,
                    'tool_params' => $step['tool_params'] ?? null
                )
            );
        }
        
        return $sub_tasks;
    }
    
    /**
     * Estimate resources needed
     * 
     * @param array $plan Execution plan
     * @return array Resource estimation
     */
    public function estimate_resources($plan) {
        $total_steps = $plan['total_steps'] ?? 1;
        
        // Count tool calls
        $tool_calls = 0;
        $ai_generations = 0;
        
        foreach ($plan['steps'] ?? array() as $step) {
            if ($step['action'] === 'tool_call') {
                $tool_calls++;
            } elseif ($step['action'] === 'generate') {
                $ai_generations++;
            }
        }
        
        // Estimate time
        $time_map = array(
            'simple' => 'short (10-30s)',
            'medium' => 'medium (30-90s)',
            'complex' => 'long (90-300s)'
        );
        
        return array(
            'total_steps' => $total_steps,
            'tool_calls' => $tool_calls,
            'ai_generations' => $ai_generations,
            'estimated_time' => $time_map[$plan['complexity'] ?? 'medium'] ?? 'medium',
            'can_execute_parallel' => $plan['parallel_execution_possible'] ?? false,
            'complexity' => $plan['complexity'] ?? 'medium'
        );
    }
    
    /**
     * Execute with planning model
     * 
     * @param string $prompt Prompt
     * @param array $options Options
     * @return array Result
     */
    private function execute_with_planning_model($prompt, $options = array()) {
        foreach ($this->planning_models as $model_combo) {
            $provider = $this->manager->get_provider($model_combo['provider']);
            
            if (!$provider) {
                continue;
            }
            
            $messages = array(
                array('role' => 'user', 'content' => $prompt)
            );
            
            $result = $provider->chat_completion($messages, array_merge(array(
                'model' => $model_combo['model'],
                'max_tokens' => 2000
            ), $options));
            
            if ($result['success'] && !empty($result['content'])) {
                return $result;
            }
        }
        
        return array(
            'success' => false,
            'error' => 'All planning models failed'
        );
    }
}
