#!/usr/bin/env php
<?php
/**
 * PipelineTimer 与日志字段辅助验证
 */
if (PHP_SAPI !== 'cli') {
    exit(1);
}

require_once dirname(__DIR__) . '/lib/Cloak/PipelineTimer.php';
require_once dirname(__DIR__) . '/lib/DbHelper.php';

$failed = 0;

CloakPipelineTimer::init();
CloakPipelineTimer::stage('阶段A');
usleep(2000);
CloakPipelineTimer::stage('阶段B');
usleep(1000);
$payload = CloakPipelineTimer::finish();

if (empty($payload['total_ms']) || $payload['total_ms'] <= 0) {
    echo "FAIL: total_ms\n";
    $failed++;
}
if (count($payload['stages'] ?? []) < 2) {
    echo "FAIL: stages count\n";
    $failed++;
}

$text = cloak_visitor_log_format_timing(json_encode($payload, JSON_UNESCAPED_UNICODE));
if ($text === '' || strpos($text, '阶段A') === false) {
    echo "FAIL: format timing text\n";
    $failed++;
}

echo json_encode(['ok' => $failed === 0], JSON_UNESCAPED_UNICODE) . "\n";
exit($failed > 0 ? 1 : 0);
