<?php
/**
 * AI Auto Tool - Lazy Loading System
 * 
 * Lazy loading system tích hợp với autoloader
 * Chỉ load classes khi thực sự cần thiết
 * 
 * @package AI Auto Tool
 * @version 2.3.0
 */

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

class AIAutoTool_LazyLoader {
    
    /**
     * Lazy loading registry
     * @var array
     */
    private static $lazyRegistry = array();
    
    /**
     * Loaded features
     * @var array
     */
    private static $loadedFeatures = array();
    
    /**
     * Feature dependencies
     * @var array
     */
    private static $featureDependencies = array();
    
    /**
     * Initialize lazy loading system
     */
    public static function init() {
        // Check if minimal mode is enabled
        $minimal_mode = get_option('aiautotool_autoloader_minimal_mode', 'false') === 'true';
        
        if ($minimal_mode) {
            // In minimal mode, only load core features
            add_action('init', array(__CLASS__, 'loadCoreOnly'), 5);
        } else {
            // Register lazy loading hooks
            add_action('init', array(__CLASS__, 'registerLazyHooks'), 5);
            add_action('wp_loaded', array(__CLASS__, 'loadRequiredFeatures'), 10);
            add_action('admin_init', array(__CLASS__, 'loadAdminFeatures'), 5);
        }
        
        // Initialize feature registry
        self::initFeatureRegistry();
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
    }
    
    /**
     * Initialize feature registry
     */
    private static function initFeatureRegistry() {
        self::$lazyRegistry = array(
            // // Core features (always loaded)
            'core' => array(
                'classes' => array(
                    'rendersetting', // Must be loaded first
                    'AIAutoTool\\Core\\Plugin',
                    'AIAutoTool\\Core\\Settings',
                    'AIAutoTool\\Core\\API',
                ),
                'files' => array(
                    'lib/setting.php', // Load rendersetting first
                    'lib/aiautotool_notice_control.php', // Load notice control
                    'lib/boxf.php', // Load AutoToolBox
                    'lib/bard.php', // Load BardGenContent
                    'lib/AIautotool_logall.php', // Load AIautoTool_log
                    'inc/canonical.php',
                    'inc/ssl.php',
                ),
                'priority' => 1,
            ),
            
            // // Conditional features
            'keyword_autopost' => array(
                'classes' => array(
                    'AIAutoTool\\Legacy\\KeywordAutopost',
                ),
                'files' => array(
                    'inc/keyword-autopost.php',
                ),
                'option' => 'keyword_autopost_active',
                'priority' => 2,
            ),
            
            'images' => array(
                'classes' => array(
                    'AIAutoTool\\Legacy\\Images',
                ),
                'files' => array(
                    'inc/images.php',
                ),
                'option' => 'images_active',
                'priority' => 2,
            ),
            
            'singleai' => array(
                'classes' => array(
                    'AIAutoTool\\Legacy\\SingleAI',
                ),
                'files' => array(
                    'inc/singleai.php',
                ),
                'option' => 'singleai_active',
                'priority' => 2,
            ),
            
            // 'ai_providers' => array(
            //     'classes' => array(
            //         'AIAutoTool\\AIProviders\\Manager',
            //         'AIAutoTool\\AIProviders\\OpenAI',
            //         'AIAutoTool\\AIProviders\\Gemini',
            //     ),
            //     'files' => array(
            //         'inc/ai-providers/index.php',
            //     ),
            //     'option' => 'ai_providers_active',
            //     'priority' => 2,
            // ),
            
            'extra_config' => array(
                'classes' => array(
                    'AIAutoTool\\ExtraConfig\\Manager',
                    'AIAutoTool\\ExtraConfig\\Security',
                    'AIAutoTool\\ExtraConfig\\SettingsRegistry',
                ),
                'files' => array(
                    'inc/extra-config/bootstrap.php',
                ),
                'option' => 'extra_config_active',
                'priority' => 2,
            ),
            
            // // Admin features
            'admin_features' => array(
                'classes' => array(
                    'AIAutoTool\\Core\\FeatureManager',
                    'AIAutoTool\\Core\\Migration',
                    'AIAutoTool\\Core\\MenuManager',
                ),
                'files' => array(
                    'inc/feature-manager.php',
                    'inc/migration.php',
                    'inc/menu-manager.php',
                ),
                'condition' => 'is_admin',
                'priority' => 1,
            ),
            
            // Lazy-loaded features
            'parsing' => array(
                'classes' => array(
                    'AIAutoTool\\Lib\\Parsedown',
                ),
                'files' => array(
                    'lib/Parsedown.php',
                ),
                'trigger' => 'parsing_needed',
                'priority' => 5,
            ),
            
            'minification' => array(
                'classes' => array(
                    'AIAutoTool\\Lib\\MinifyJS',
                ),
                'files' => array(
                    'lib/minify-js.php',
                ),
                'trigger' => 'minification_needed',
                'priority' => 5,
            ),
        );
        
        // Initialize feature dependencies
        self::$featureDependencies = array(
            'ai_providers' => array(),
            'extra_config' => array(),
            'keyword_autopost' => array(),
            'images' => array(),
            'singleai' => array(),
        );
    }
    
    /**
     * Load only core features in minimal mode
     */
    public static function loadCoreOnly() {
        // Load only essential core features
        self::loadFeature('core');
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
    }
    
    /**
     * Register lazy loading hooks
     */
    public static function registerLazyHooks() {
        // Load core features immediately
        self::loadFeature('core');
        
        // Register conditional loading hooks
        foreach (self::$lazyRegistry as $featureName => $config) {
            if (isset($config['option'])) {
                add_action('init', function() use ($featureName) {
                    if (self::shouldLoadFeature($featureName)) {
                        self::loadFeature($featureName);
                    }
                }, $config['priority']);
            }
        }
    }
    
    /**
     * Load required features
     */
    public static function loadRequiredFeatures() {
        // Load features based on current context
        if (is_admin()) {
            self::loadFeature('admin_features');
        }
        
        // Load features based on active options
        foreach (self::$lazyRegistry as $featureName => $config) {
            if (isset($config['option']) && self::shouldLoadFeature($featureName)) {
                self::loadFeature($featureName);
            }
        }
    }
    
    /**
     * Load admin features
     */
    public static function loadAdminFeatures() {
        if (!is_admin()) {
            return;
        }
        
        // Load admin-specific features
        $adminFeatures = array(
            'feature_manager',
            'migration',
            'cron_status',
        );
        
        foreach ($adminFeatures as $feature) {
            if (isset(self::$lazyRegistry[$feature])) {
                self::loadFeature($feature);
            }
        }
    }
    
    /**
     * Check if feature should be loaded
     */
    private static function shouldLoadFeature($featureName) {
        if (!isset(self::$lazyRegistry[$featureName])) {
            return false;
        }
        
        $config = self::$lazyRegistry[$featureName];
        
        // Check option-based loading
        if (isset($config['option'])) {
            return get_option($config['option'], 'false') === 'true';
        }
        
        // Check condition-based loading
        if (isset($config['condition'])) {
            $condition = $config['condition'];
            if ($condition === 'is_admin') {
                return is_admin();
            }
        }
        
        // Check trigger-based loading
        if (isset($config['trigger'])) {
            return get_option($config['trigger'], 'false') === 'true';
        }
        
        return false;
    }
    
    /**
     * Load feature with dependencies
     */
    public static function loadFeature($featureName) {
        if (in_array($featureName, self::$loadedFeatures)) {
            return true;
        }
        
        if (!isset(self::$lazyRegistry[$featureName])) {
            return false;
        }
        
        // Load dependencies first
        if (isset(self::$featureDependencies[$featureName])) {
            foreach (self::$featureDependencies[$featureName] as $dependency) {
                if (!in_array($dependency, self::$loadedFeatures)) {
                    self::loadFeature($dependency);
                }
            }
        }
        
        $config = self::$lazyRegistry[$featureName];
        $pluginDir = plugin_dir_path(__FILE__) . '../';
        
        // Load files
        if (isset($config['files'])) {
            foreach ($config['files'] as $file) {
                $filePath = $pluginDir . $file;
                if (file_exists($filePath)) {
                    require_once $filePath;
                    
                    if (defined('WP_DEBUG') && WP_DEBUG) {
                    }
                }
            }
        }
        
        // Load classes (will be handled by autoloader)
        if (isset($config['classes'])) {
            foreach ($config['classes'] as $className) {
                if (!class_exists($className)) {
                    // Trigger autoloader
                    AIAutoTool_Autoloader::loadClass($className);
                }
            }
        }
        
        self::$loadedFeatures[] = $featureName;
        
        // Trigger feature loaded action
        do_action("aiautotool_feature_loaded_{$featureName}");
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
        }
        
        return true;
    }
    
    /**
     * Load feature on demand
     */
    public static function loadOnDemand($featureName) {
        return self::loadFeature($featureName);
    }
    
    /**
     * Check if feature is loaded
     */
    public static function isFeatureLoaded($featureName) {
        return in_array($featureName, self::$loadedFeatures);
    }
    
    /**
     * Get loaded features
     */
    public static function getLoadedFeatures() {
        return self::$loadedFeatures;
    }
    
    /**
     * Get feature registry
     */
    public static function getFeatureRegistry() {
        return self::$lazyRegistry;
    }
    
    /**
     * Performance statistics
     */
    public static function getStats() {
        return array(
            'loaded_features' => count(self::$loadedFeatures),
            'total_features' => count(self::$lazyRegistry),
            'loaded_feature_names' => self::$loadedFeatures,
            'memory_usage' => memory_get_usage(true),
            'autoloader_stats' => AIAutoTool_Autoloader::getStats(),
        );
    }
    
    /**
     * Force load all features (for debugging)
     */
    public static function loadAllFeatures() {
        foreach (array_keys(self::$lazyRegistry) as $featureName) {
            self::loadFeature($featureName);
        }
    }
    
    /**
     * Reset loaded features (for testing)
     */
    public static function resetLoadedFeatures() {
        self::$loadedFeatures = array();
    }
}

// Initialize lazy loading system
AIAutoTool_LazyLoader::init();
?>
