<?php

namespace Licenzo\Framework\Http\Performance;

use Licenzo\Framework\Foundation\Application;

/**
 * Performance Optimizer
 * 
 * Optimizes kernel and middleware performance
 */
class Optimizer
{
    /**
     * The application instance.
     */
    protected Application $app;

    /**
     * Optimization cache.
     */
    protected array $cache = [];

    /**
     * Create a new optimizer instance.
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Optimize middleware resolution.
     */
    public function optimizeMiddleware(): void
    {
        if ($this->app->bound('middleware.registry')) {
            $registry = $this->app->make('middleware.registry');
            
            // Pre-resolve commonly used middleware
            $commonMiddleware = ['auth', 'cors', 'validate', 'csrf'];
            
            foreach ($commonMiddleware as $alias) {
                if ($registry->has($alias)) {
                    $class = $registry->resolve($alias);
                    if ($class && !$this->app->bound($class)) {
                        $this->app->singleton($class);
                    }
                }
            }
        }
    }

    /**
     * Optimize route matching.
     */
    public function optimizeRoutes(): void
    {
        if ($this->app->bound('router')) {
            $router = $this->app->make('router');
            
            // Enable route caching in production
            if (!defined('WP_DEBUG') || !WP_DEBUG) {
                $router->cache(true);
            }
        }
    }

    /**
     * Optimize memory usage.
     */
    public function optimizeMemory(): void
    {
        // Clear unnecessary data
        $this->clearTemporaryData();
        
        // Optimize object cache if available
        $this->optimizeObjectCache();
        
        // Force garbage collection if memory usage is high
        if (memory_get_usage(true) > $this->getMemoryThreshold()) {
            gc_collect_cycles();
        }
    }

    /**
     * Clear temporary data.
     */
    protected function clearTemporaryData(): void
    {
        // Clear internal cache
        $this->cache = [];
        
        // Clear WordPress transients older than 1 hour
        $this->clearOldTransients();
    }

    /**
     * Clear old WordPress transients.
     */
    protected function clearOldTransients(): void
    {
        global $wpdb;
        
        // Only run cleanup occasionally to avoid performance impact
        if (rand(1, 100) > 5) { // 5% chance
            return;
        }
        
        $wpdb->query($wpdb->prepare("
            DELETE FROM {$wpdb->options} 
            WHERE option_name LIKE %s 
            AND option_name LIKE %s
        ", '_transient_timeout_%', '%' . (time() - 3600)));
    }

    /**
     * Optimize object cache.
     */
    protected function optimizeObjectCache(): void
    {
        // If WordPress object cache is available, optimize it
        if (function_exists('wp_cache_flush_group')) {
            // Flush specific cache groups that might be stale
            wp_cache_flush_group('licenzo_temp');
        }
    }

    /**
     * Get memory threshold for optimization.
     */
    protected function getMemoryThreshold(): int
    {
        $limit = ini_get('memory_limit');
        if ($limit === '-1') {
            return PHP_INT_MAX;
        }
        
        $bytes = $this->convertToBytes($limit);
        return (int) ($bytes * 0.8); // 80% of memory limit
    }

    /**
     * Convert memory limit string to bytes.
     */
    protected function convertToBytes(string $value): int
    {
        $value = trim($value);
        $last = strtolower($value[strlen($value) - 1]);
        $value = (int) $value;
        
        switch ($last) {
            case 'g':
                $value *= 1024;
            case 'm':
                $value *= 1024;
            case 'k':
                $value *= 1024;
        }
        
        return $value;
    }

    /**
     * Optimize database queries.
     */
    public function optimizeDatabase(): void
    {
        // Enable WordPress query optimization
        if (!defined('WP_DEBUG') || !WP_DEBUG) {
            // Disable query debugging in production
            if (defined('SAVEQUERIES')) {
                define('SAVEQUERIES', false);
            }
        }
        
        // Optimize WordPress options autoload
        $this->optimizeAutoloadOptions();
    }

    /**
     * Optimize WordPress autoload options.
     */
    protected function optimizeAutoloadOptions(): void
    {
        global $wpdb;
        
        // Only run occasionally to avoid performance impact
        if (rand(1, 1000) > 1) { // 0.1% chance
            return;
        }
        
        // Find large autoload options that might slow down WordPress
        $results = $wpdb->get_results("
            SELECT option_name, LENGTH(option_value) as size 
            FROM {$wpdb->options} 
            WHERE autoload = 'yes' 
            AND LENGTH(option_value) > 1000 
            ORDER BY size DESC 
            LIMIT 10
        ");
        
        foreach ($results as $option) {
            // Log large autoload options for review
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log("[Licenzo] Large autoload option: {$option->option_name} ({$option->size} bytes)");
            }
        }
    }

    /**
     * Run all optimizations.
     */
    public function optimize(): void
    {
        $this->optimizeMiddleware();
        $this->optimizeRoutes();
        $this->optimizeMemory();
        $this->optimizeDatabase();
    }

    /**
     * Get optimization statistics.
     */
    public function getStats(): array
    {
        return [
            'memory_usage' => memory_get_usage(true),
            'peak_memory' => memory_get_peak_usage(true),
            'memory_limit' => ini_get('memory_limit'),
            'memory_threshold' => $this->getMemoryThreshold(),
            'cache_size' => count($this->cache),
            'optimization_enabled' => !defined('WP_DEBUG') || !WP_DEBUG,
        ];
    }

    /**
     * Check if optimization is needed.
     */
    public function needsOptimization(): bool
    {
        $memoryUsage = memory_get_usage(true);
        $threshold = $this->getMemoryThreshold();
        
        return $memoryUsage > ($threshold * 0.7); // 70% of threshold
    }

    /**
     * Schedule optimization.
     */
    public function scheduleOptimization(): void
    {
        // Use WordPress cron to schedule optimization
        if (!wp_next_scheduled('licenzo_optimize_performance')) {
            wp_schedule_event(time(), 'hourly', 'licenzo_optimize_performance');
        }
        
        // Register the optimization callback
        add_action('licenzo_optimize_performance', [$this, 'optimize']);
    }

    /**
     * Clear scheduled optimization.
     */
    public function clearScheduledOptimization(): void
    {
        wp_clear_scheduled_hook('licenzo_optimize_performance');
    }
}
