<?php

namespace XZD\AI\V5\Analytics;

use XZD\AI\V5\Core\Config;

/**
 * Worker 性能监控 — 收集多Worker系统的运行指标
 *
 * 监控指标：
 *   - 队列深度（待处理文章数）
 *   - Worker活跃数
 *   - 平均每篇文章处理时间
 *   - AI 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'         => Config::instance()->int('api_rate_limit.capacity', 5),
                'fill_rate'        => 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'      => Config::instance()->int('worker.max_concurrent', 3),
            'timestamp'        => current_time('mysql'),
        ];
    }

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

        if (function_exists('as_get_scheduled_actions')) {
            $activeWorkers = count(as_get_scheduled_actions([
                'hook'     => 'xzd_worker_process',
                'status'   => \ActionScheduler_Store::STATUS_RUNNING,
                'group'    => 'xzd_worker',
                'per_page' => -1,
            ]));
        }

        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视为不健康
        ];
    }
}
