<?php

namespace XZD\AI\V5\Analytics;

/**
 * Worker 性能监控 — 收集多Worker系统的运行指标（队列深度、Worker活跃数、平均处理时间、API调用成功率、内存峰值）
 */
class WorkerMonitor
{
    /**
     * 获取完整的Worker运行状态快照
     */
    public static function getStatus(): array
    {
        $statsKey = 'xzd_worker_stats_' . date('Y-m-d');
        $stats = get_transient($statsKey);
        if (!$stats) {
            $stats = ['completed' => 0, 'total_elapsed_ms' => 0, 'peak_memory' => 0, 'last_update' => 0];
        }

        // 队列状态
        $queueStatus = [];
        if (class_exists(\XZD\AI\V5\Tools\QueueManager::class)) {
            $queueStatus = \XZD\AI\V5\Tools\QueueManager::getQueueStatus();
        }

        // API 速率限制器状态
        $rateLimiterStatus = [];
        if (class_exists(\XZD\AI\V5\Core\ApiRateLimiter::class)) {
            $limiter = \XZD\AI\V5\Core\ApiRateLimiter::instance();
            $rateLimiterStatus = [
                'available_tokens' => round($limiter->available(), 2),
                'capacity'         => \XZD\AI\V5\Core\Config::instance()->int('api_rate_limit.capacity', 5),
                'fill_rate'        => \XZD\AI\V5\Core\Config::instance()->get('api_rate_limit.fill_rate', 1.0),
            ];
        }

        $avgElapsedMs = $stats['completed'] > 0
            ? round($stats['total_elapsed_ms'] / $stats['completed'])
            : 0;

        return [
            'today' => [
                'completed'       => $stats['completed'],
                'avg_elapsed_ms'  => $avgElapsedMs,
                'peak_memory_mb'  => round($stats['peak_memory'] / 1024 / 1024, 1),
                'last_update'     => $stats['last_update'] ? date('Y-m-d H:i:s', $stats['last_update']) : null,
            ],
            'queue'            => $queueStatus,
            'rate_limiter'     => $rateLimiterStatus,
            'max_workers'      => \XZD\AI\V5\Core\Config::instance()->int('worker.max_concurrent', 3),
            'timestamp'        => current_time('mysql'),
        ];
    }

    /**
     * 获取轻量级心跳状态（仪表盘轮询用）
     */
    public static function getHeartbeat(): array
    {
        $queueSize = 0;
        $activeWorkers = 0;

        // 改用直接 SQL COUNT，避免全量加载 action ID
        global $wpdb;
        $tableActions = $wpdb->prefix . 'actionscheduler_actions';
        $activeWorkers = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$tableActions} WHERE hook = %s AND status = 'in-progress'",
            'xzd_worker_process'
        ));

        if (class_exists(\XZD\AI\V5\Tools\QueueManager::class)) {
            $status = \XZD\AI\V5\Tools\QueueManager::getQueueStatus();
            $queueSize = $status['queue_pending'] ?? 0;
        }

        return [
            'queue_size'     => $queueSize,
            'active_workers' => $activeWorkers,
            'healthy'        => $queueSize < 100, // 积压超过100视为不健康
        ];
    }
}
