<?php

namespace XZD\AI\V5\Core;

/**
 * WP-CLI 命令 — 支持系统 cron 触发，低流量站点也能准时运行
 *
 * 用法：
 *   wp xzd heartbeat trigger    触发心跳（系统cron用）
 *   wp xzd heartbeat status     查看心跳状态
 *   wp xzd queue status         查看队列状态
 *
 * 系统 crontab 示例（每分钟）：
 *   * * * * * cd /var/www/html && wp xzd heartbeat trigger > /dev/null 2>&1
 */
class CLI
{
    public static function register(): void
    {
        if (!defined('WP_CLI') || !WP_CLI) {
            return;
        }

        \WP_CLI::add_command('xzd heartbeat trigger', function () {
            $result = Heartbeat::tick();
            if ($result['ok']) {
                \WP_CLI::success(sprintf(
                    '心跳完成: 分发%d, 清空%d, 扫描%s, 学习%s, 耗时%.1fms',
                    $result['tasks_dispatched'],
                    $result['queue_drained'],
                    $result['scan_triggered'] ? '是' : '否',
                    $result['learning_triggered'] ? '是' : '否',
                    $result['elapsed_ms']
                ));
            } else {
                \WP_CLI::warning('心跳异常: ' . ($result['error'] ?? '未知'));
            }
        });

        \WP_CLI::add_command('xzd heartbeat status', function () {
            $status = Heartbeat::getStatus();
            $fields = [
                '最后心跳'   => $status['last_tick_at'] ?? '从未',
                '距上次(秒)' => $status['last_tick_ago_s'] ?? 'N/A',
                '下次(秒)'   => $status['next_tick_in_s'] ?? 'N/A',
                '逾期'       => $status['overdue'] ? '是' : '否',
                '队列深度'   => $status['queue_depth'],
                '健康'       => $status['healthy'] ? '是' : '否',
            ];
            \WP_CLI\Utils\format_items('table', [$fields], array_keys($fields));
        });

        \WP_CLI::add_command('xzd queue status', function () {
            global $wpdb;
            $table = $wpdb->prefix . 'actionscheduler_actions';

            $asPending = (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$table}
                 WHERE hook = 'xzd_worker_process' AND status = 'pending'"
            );
            $asRunning = (int) $wpdb->get_var(
                "SELECT COUNT(*) FROM {$table}
                 WHERE hook = 'xzd_worker_process' AND status = 'in-progress'"
            );
            $pqSize = class_exists(PendingQueue::class) ? PendingQueue::size() : 0;

            $fields = [
                'AS待处理'  => $asPending,
                'AS进行中'  => $asRunning,
                'PendingQ'  => $pqSize,
                '总积压'     => $asPending + $pqSize,
                '并发数'     => Plugin::calcDynamicConcurrency(),
            ];
            \WP_CLI\Utils\format_items('table', [$fields], array_keys($fields));
        });
    }
}
