<?php
/**
 * AI Helper
 * Global helper class để gọi AI từ bất kỳ đâu trong plugin
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

class AIAutotool_AI_Helper {
    
    /**
     * Static flag to track initialization
     */
    private static $initialized = false;
    
    /**
     * Ensure AI Providers module is initialized
     * This is a safety net in case the class is accessed before index.php loads
     */
    private static function ensure_initialized() {
        if (self::$initialized) {
            return;
        }
        
        // If Manager class doesn't exist, try to load the index.php file
        if (!class_exists('AIAutotool_AI_Provider_Manager')) {
            $index_file = dirname(__FILE__) . '/index.php';
            if (file_exists($index_file)) {
                require_once $index_file;
            }
        }
        
        self::$initialized = true;
    }
    
    /**
     * Generate text from prompt (Simple helper)
     * 
     * @param string $prompt Text prompt
     * @param array $options Optional parameters
     * @return array Response with 'success', 'content', 'error'
     */
    public static function generate($prompt, $options = array()) {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $route = method_exists($manager, 'get_provider_for_request') ? $manager->get_provider_for_request() : false;
        $provider = $route && isset($route['provider']) ? $route['provider'] : $manager->get_active_provider();
        
        if (!$provider) {
            return array(
                'success' => false,
                'error' => 'No AI provider configured'
            );
        }
        
        // Use active model if not specified
        if (!isset($options['model'])) {
            $options['model'] = $route && isset($route['model']) ? $route['model'] : $manager->get_active_model();
        }
        
        return $provider->generate($prompt, $options);
    }
    
    /**
     * Chat completion with messages
     * 
     * @param array $messages Array of messages with 'role' and 'content'
     * @param array $options Optional parameters
     * @return array Response
     */
    public static function chat($messages, $options = array()) {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $route = method_exists($manager, 'get_provider_for_request') ? $manager->get_provider_for_request() : false;
        $provider = $route && isset($route['provider']) ? $route['provider'] : $manager->get_active_provider();
        
        if (!$provider) {
            return array(
                'success' => false,
                'error' => 'No AI provider configured'
            );
        }
        
        // Use active model if not specified
        if (!isset($options['model'])) {
            $options['model'] = $route && isset($route['model']) ? $route['model'] : $manager->get_active_model();
        }
        
        // 🔍 DEBUG: Log which provider is being used
        
        return $provider->chat_completion($messages, $options);
    }
    
    /**
     * Generate with specific provider
     * 
     * @param string $provider_id Provider ID (openai, gemini, llm7)
     * @param string $prompt Text prompt
     * @param array $options Optional parameters
     * @return array Response
     */
    public static function generate_with_provider($provider_id, $prompt, $options = array()) {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $provider = $manager->get_provider($provider_id);
        
        if (!$provider) {
            return array(
                'success' => false,
                'error' => "Provider '{$provider_id}' not found"
            );
        }
        
        if (!$provider->is_configured()) {
            return array(
                'success' => false,
                'error' => "Provider '{$provider_id}' not configured"
            );
        }
        
        return $provider->generate($prompt, $options);
    }
    
    /**
     * Generate with specific model
     * 
     * @param string $model Model name
     * @param string $prompt Text prompt
     * @param array $options Optional parameters
     * @return array Response
     */
    public static function generate_with_model($model, $prompt, $options = array()) {
        $options['model'] = $model;
        return self::generate($prompt, $options);
    }
    
    /**
     * Chat completion with specific provider
     * 
     * @param string $provider_id Provider ID (pollinations, gemini, openai, etc.)
     * @param array $messages Array of messages with 'role' and 'content'
     * @param array $options Optional parameters
     * @return array Response
     */
    public static function chat_with_provider($provider_id, $messages, $options = array()) {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $provider = $manager->get_provider($provider_id);
        
        if (!$provider) {
            return array(
                'success' => false,
                'error' => "Provider '{$provider_id}' not found"
            );
        }
        
        if (!$provider->is_configured()) {
            return array(
                'success' => false,
                'error' => "Provider '{$provider_id}' not configured"
            );
        }
        
        // Use provider's default model if not specified
        if (!isset($options['model'])) {
            $options['model'] = $provider->get_default_model();
        }
        
        return $provider->chat_completion($messages, $options);
    }
    
    /**
     * Chat completion with specific provider and model
     * Dễ dàng chuyển đổi provider và model trong một lần gọi
     * 
     * @param string $provider_id Provider ID (pollinations, gemini, openai, etc.)
     * @param string $model Model name
     * @param array $messages Array of messages with 'role' and 'content'
     * @param array $options Optional parameters (temperature, max_tokens, etc.)
     * @return array Response with 'success', 'content', 'error'
     * 
     * @example
     * // Gọi Pollinations với model gemini-search
     * $result = AIAutotool_AI_Helper::chat_with_provider_and_model(
     *     'pollinations',
     *     'gemini-search',
     *     array(
     *         array('role' => 'user', 'content' => 'Hello!')
     *     )
     * );
     */
    public static function chat_with_provider_and_model($provider_id, $model, $messages, $options = array()) {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $provider = $manager->get_provider($provider_id);
        
        if (!$provider) {
            return array(
                'success' => false,
                'error' => "Provider '{$provider_id}' not found. Available providers: " . implode(', ', array_keys($manager->get_all_providers()))
            );
        }
        
        if (!$provider->is_configured()) {
            return array(
                'success' => false,
                'error' => "Provider '{$provider_id}' not configured. Please check API key settings."
            );
        }
        
        // Set model in options
        $options['model'] = $model;
        
        // Log for debugging
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        return $provider->chat_completion($messages, $options);
    }
    
    /**
     * Generate text with specific provider and model
     * Dễ dàng chuyển đổi provider và model trong một lần gọi
     * 
     * @param string $provider_id Provider ID (pollinations, gemini, openai, etc.)
     * @param string $model Model name
     * @param string $prompt Text prompt
     * @param array $options Optional parameters (temperature, max_tokens, etc.)
     * @return array Response with 'success', 'content', 'error'
     * 
     * @example
     * // Gọi Pollinations với model gemini-search
     * $result = AIAutotool_AI_Helper::generate_with_provider_and_model(
     *     'pollinations',
     *     'gemini-search',
     *     'What is WordPress?'
     * );
     */
    public static function generate_with_provider_and_model($provider_id, $model, $prompt, $options = array()) {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $provider = $manager->get_provider($provider_id);
        
        if (!$provider) {
            return array(
                'success' => false,
                'error' => "Provider '{$provider_id}' not found. Available providers: " . implode(', ', array_keys($manager->get_all_providers()))
            );
        }
        
        if (!$provider->is_configured()) {
            return array(
                'success' => false,
                'error' => "Provider '{$provider_id}' not configured. Please check API key settings."
            );
        }
        
        // Set model in options
        $options['model'] = $model;
        
        // Log for debugging
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        return $provider->generate($prompt, $options);
    }
    
    /**
     * Check if AI is available
     * 
     * @return bool
     */
    public static function is_available() {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        return $manager->has_configured_provider();
    }
    
    /**
     * Get active provider info
     * 
     * @return array|null
     */
    public static function get_active_info() {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $provider = $manager->get_active_provider();
        
        if (!$provider) {
            return null;
        }
        
        return array(
            'provider_id' => $provider->get_id(),
            'provider_name' => $provider->get_name(),
            'model' => $manager->get_active_model(),
            'configured' => $provider->is_configured(),
            'routing_mode' => method_exists($manager, 'get_provider_routing_mode') ? $manager->get_provider_routing_mode() : 'single'
        );
    }
    
    /**
     * Test connection
     * 
     * @return array Response with 'success' and 'message'
     */
    public static function test_connection() {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $provider = $manager->get_active_provider();
        
        if (!$provider) {
            return array(
                'success' => false,
                'message' => 'No AI provider configured'
            );
        }
        
        return $provider->test_connection();
    }
    
    /**
     * Backward compatibility wrapper for gemini_generate
     * (Keep for existing code that uses AIAutotool_API_Helper::gemini_generate)
     * 
     * @param string $prompt
     * @param array $options
     * @return array|WP_Error
     */
    public static function gemini_generate($prompt, $options = array()) {
        $result = self::generate_with_provider('gemini', $prompt, $options);
        
        if (!$result['success']) {
            return new WP_Error('ai_error', $result['error']);
        }
        
        return $result;
    }
    
    /**
     * Backward compatibility wrapper for openai_generate
     * 
     * @param string $prompt
     * @param array $options
     * @return array|WP_Error
     */
    public static function openai_generate($prompt, $options = array()) {
        $result = self::generate_with_provider('openai', $prompt, $options);
        
        if (!$result['success']) {
            return new WP_Error('ai_error', $result['error']);
        }
        
        return $result;
    }
    
    /**
     * Smart generate - Auto select best provider
     * Priority: Pollinations.ai (free) > Gemini > OpenAI
     * 
     * @param string $prompt
     * @param array $options
     * @return array
     */
    public static function smart_generate($prompt, $options = array()) {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        
        // Try Pollinations.ai first (free)
        $pollinations = $manager->get_provider('pollinations');
        if (!$pollinations) {
            // Backward compatibility: try 'llm7'
            $pollinations = $manager->get_provider('llm7');
        }
        if ($pollinations && $pollinations->is_configured()) {
            $result = $pollinations->generate($prompt, $options);
            if ($result['success']) {
                return $result;
            }
        }
        
        // Try Gemini
        $gemini = $manager->get_provider('gemini');
        if ($gemini && $gemini->is_configured()) {
            $result = $gemini->generate($prompt, $options);
            if ($result['success']) {
                return $result;
            }
        }
        
        // Try OpenAI
        $openai = $manager->get_provider('openai');
        if ($openai && $openai->is_configured()) {
            return $openai->generate($prompt, $options);
        }
        
        return array(
            'success' => false,
            'error' => 'No AI provider available'
        );
    }
    
    /**
     * Get all available models across providers
     * 
     * @return array
     */
    public static function get_all_models() {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $all_models = array();
        
        foreach ($manager->get_configured_providers() as $id => $provider) {
            $models = $provider->get_available_models();
            foreach ($models as $model_id => $model_name) {
                $all_models[$model_id] = array(
                    'name' => $model_name,
                    'provider' => $provider->get_name(),
                    'provider_id' => $id
                );
            }
        }
        
        return $all_models;
    }
    
    /**
     * Get all available providers with their info
     * 
     * @return array Array of provider info with 'id', 'name', 'configured', 'models', 'default_model'
     */
    public static function get_all_providers() {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        return $manager->get_providers_info();
    }
    
    /**
     * Get available models for a specific provider
     * 
     * @param string $provider_id Provider ID
     * @return array|false Array of models (model_id => model_name) or false if provider not found
     */
    public static function get_provider_models($provider_id) {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $provider = $manager->get_provider($provider_id);
        
        if (!$provider) {
            return false;
        }
        
        return $provider->get_available_models();
    }
    
    /**
     * Check if a provider is configured
     * 
     * @param string $provider_id Provider ID
     * @return bool
     */
    public static function is_provider_configured($provider_id) {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $provider = $manager->get_provider($provider_id);
        
        if (!$provider) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
            }
            return false;
        }
        
        $is_configured = $provider->is_configured();
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            if (!$is_configured) {
            }
        }
        
        return $is_configured;
    }
    
    /**
     * Check if a model exists for a provider
     * 
     * @param string $provider_id Provider ID
     * @param string $model Model ID
     * @return bool
     */
    public static function is_model_available($provider_id, $model) {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();
        $provider = $manager->get_provider($provider_id);
        
        if (!$provider) {
            return false;
        }
        
        $models = $provider->get_available_models();
        return isset($models[$model]);
    }

    /**
     * Generate image with an image-capable provider.
     */
    public static function generate_image($prompt, $options = array()) {
        self::ensure_initialized();
        $manager = AIAutotool_AI_Provider_Manager::get_instance();

        $provider_id = isset($options['provider']) ? sanitize_text_field($options['provider']) : '';
        $model = isset($options['model']) ? sanitize_text_field($options['model']) : '';
        $route = method_exists($manager, 'get_image_provider_for_request') ? $manager->get_image_provider_for_request($provider_id, $model) : false;

        if (!$route || empty($route['provider'])) {
            $pollinations = $manager->get_provider('pollinations');
            if ($pollinations && $pollinations->supports_capability('image_generation')) {
                $image_models = $pollinations->get_image_models();
                $route = array(
                    'provider' => $pollinations,
                    'provider_id' => 'pollinations',
                    'model' => !empty($image_models) ? key($image_models) : 'flux',
                );
            } else {
                return array(
                    'success' => false,
                    'error' => 'No image-capable AI provider configured'
                );
            }
        }

        $options['provider'] = $route['provider_id'];
        $options['model'] = $route['model'];

        return $route['provider']->generate_image($prompt, $options);
    }
    
    /**
     * Generate using AI Agent (automatic provider/model selection with fallback)
     * 
     * @param string|array $prompt Text prompt or messages array
     * @param array $options Optional parameters (use_case, provider, model, etc.)
     * @return array Response with 'success', 'content', 'error', 'provider', 'model', 'use_case'
     * 
     * @example
     * // Automatic selection based on prompt
     * $result = AIAutotool_AI_Helper::agent_generate('Tìm kiếm thông tin về WordPress');
     * 
     * // Force specific use case
     * $result = AIAutotool_AI_Helper::agent_generate('Phân tích dữ liệu', array('use_case' => 'reasoning'));
     */
    public static function agent_generate($prompt, $options = array()) {
        self::ensure_initialized();
        
        if (!class_exists('AIAutotool_AI_Agent')) {
            // Fallback to regular generate if agent not available
            return self::generate($prompt, $options);
        }
        
        $agent = AIAutotool_AI_Agent::get_instance();
        return $agent->generate($prompt, $options);
    }
    
    /**
     * Chat completion using AI Agent (automatic provider/model selection with fallback)
     * 
     * @param array $messages Array of messages with 'role' and 'content'
     * @param array $options Optional parameters (use_case, provider, model, etc.)
     * @return array Response with 'success', 'content', 'error', 'provider', 'model', 'use_case'
     * 
     * @example
     * // Automatic selection
     * $result = AIAutotool_AI_Helper::agent_chat(array(
     *     array('role' => 'user', 'content' => 'Viết code PHP để kết nối database')
     * ), array('use_case' => 'code'));
     */
    public static function agent_chat($messages, $options = array()) {
        self::ensure_initialized();
        
        if (!class_exists('AIAutotool_AI_Agent')) {
            // Fallback to regular chat if agent not available
            return self::chat($messages, $options);
        }
        
        $agent = AIAutotool_AI_Agent::get_instance();
        return $agent->chat($messages, $options);
    }
    
    /**
     * Get AI Agent instance
     * 
     * @return AIAutotool_AI_Agent|null
     */
    public static function get_agent() {
        self::ensure_initialized();
        
        if (!class_exists('AIAutotool_AI_Agent')) {
            return null;
        }
        
        return AIAutotool_AI_Agent::get_instance();
    }
}
