<?php
/**
 * 虚拟设备检测规则引擎回归（CLI 输出 JSON）
 */
$root = dirname(__DIR__);

function render_dist_index_virtual($root, $virtualLevel)
{
    $cmd = escapeshellarg(PHP_BINARY) . ' -r ' . escapeshellarg(
        '$root=' . var_export($root, true) . ';'
        . '$_GET=["c"=>"index"];'
        . 'include $root . "/cong.php";'
        . 'include $root . "/config/ConfigLoader.php";'
        . 'ConfigLoader::loadByName("index", $root);'
        . 'runkit7_constant_redefine("IS_VIRTUAL", ' . var_export((string) $virtualLevel, true) . ');'
        . 'ob_start();include $root."/dist/index.php";echo ob_get_clean();'
    ) . ' 2>&1';
    return shell_exec($cmd);
}

function render_dist_index_simple($root)
{
    $_GET = ['c' => 'index'];
    ob_start();
    include $root . '/dist/index.php';
    return ob_get_clean();
}

$tests = [];

$offOut = render_dist_index_simple($root);
$tests['off_no_engine'] = strpos($offOut, 'CloakVirtualDetect') === false;
$tests['off_has_finish'] = strpos($offOut, 'cloakFinishFingerprint') !== false;

// 临时写入带 IS_VIRTUAL 的配置片段：直接 include 引擎文件测输出
$engineOut = (function () use ($root) {
    ob_start();
    include $root . '/resources/virtual_device_detect.inc.php';
    return ob_get_clean();
})();
$tests['engine_has_mobile_only'] = strpos($engineOut, 'mobileOnly') !== false;
$tests['engine_has_sensors'] = strpos($engineOut, 'checkMotionSensors') !== false;
$tests['engine_no_performance_bench'] = strpos($engineOut, 'detectVMByPerformance') === false;
$tests['engine_has_v13'] = strpos($engineOut, "'V13'") !== false;
$tests['engine_has_v24'] = strpos($engineOut, "'V24'") !== false;

// 若 index 配置 IS_VIRTUAL>0 则 dist 会带引擎；否则仅验证 off 路径
$onOut = render_dist_index_simple($root);
$tests['dist_has_finish_fn'] = strpos($onOut, 'cloakFinishFingerprint') !== false;
$tests['dist_no_old_inline'] = strpos($onOut, 'isVMByHardware') === false;
$tests['dist_no_fatal'] = stripos($onOut, 'Fatal error') === false;

echo json_encode(['ok' => !in_array(false, $tests, true), 'tests' => $tests], JSON_UNESCAPED_UNICODE) . "\n";
