<?php
/**
 * cloakjs 基础/加强模式输出回归（CLI 输出 JSON）
 */
$root = dirname(__DIR__);

function render_cloakjs($root, $enhanced)
{
    if (!defined('CLOAK_RISK_ENHANCED')) {
        define('CLOAK_RISK_ENHANCED', $enhanced ? 'ON' : 'OFF');
    }
    $v_infoStub       = new stdClass();
    $v_infoStub->v_ip = '203.0.113.50';
    $v_infoStub->v_country = 'US';
    $log_idStub       = 4242;
    ob_start();
    extract(['v_info' => $v_infoStub, 'log_id' => $log_idStub], EXTR_SKIP);
    include $root . '/cloakjs.php';
    return ob_get_clean();
}

$tests = [];

$basicOut = render_cloakjs($root, false);
$tests['basic_no_webgpu_fn'] = strpos($basicOut, 'getWebGPUFingerprint') === false;
$tests['basic_no_uaparser_lib'] = strpos($basicOut, 'UAParser.VERSION') === false;
$tests['basic_has_f_check'] = strpos($basicOut, 'f_check.php') !== false;
$tests['basic_has_ip'] = strpos($basicOut, '203.0.113.50') !== false;
$tests['basic_no_canvas_fp'] = strpos($basicOut, 'function cloakCanvasFingerprint') === false;
$tests['basic_no_webgl_deep'] = strpos($basicOut, 'function cloakWebglDeepFingerprint') === false;
$tests['basic_no_enhanced_apply_fn'] = strpos($basicOut, 'function cloakApplyEnhancedFingerprint') === false;
$tests['basic_risk_enhanced_false'] = strpos($basicOut, '__cloakRiskEnhanced = false') !== false;
$tests['basic_nulls_heavy_fields'] = strpos($basicOut, '_0x5aa8d7.set("canvas", null)') !== false;
$tests['basic_no_fatal'] = stripos($basicOut, 'Fatal error') === false;

// 第二次渲染需在新进程或重置常量不可行；加强模式单独子进程
$enhCmd = escapeshellarg(PHP_BINARY) . ' -r '
    . escapeshellarg(
        '$root=' . var_export($root, true) . ';'
        . 'define("CLOAK_RISK_ENHANCED","ON");'
        . '$v_info=new stdClass;$v_info->v_ip="203.0.113.51";$v_info->v_country="US";'
        . '$log_id=5252;ob_start();include $root."/cloakjs.php";echo ob_get_clean();'
    ) . ' 2>&1';
$enhOut = shell_exec($enhCmd);
$tests['enhanced_has_webgpu_fn'] = strpos((string) $enhOut, 'getWebGPUFingerprint') !== false;
$tests['enhanced_has_uaparser_lib'] = strpos((string) $enhOut, 'UAParser.VERSION') !== false;
$tests['enhanced_has_f_check'] = strpos((string) $enhOut, 'f_check.php') !== false;
$tests['enhanced_has_enhanced_fn'] = strpos((string) $enhOut, 'function cloakApplyEnhancedFingerprint') !== false;
$tests['enhanced_has_canvas_fp'] = strpos((string) $enhOut, 'function cloakCanvasFingerprint') !== false;
$tests['enhanced_risk_enhanced_true'] = strpos((string) $enhOut, '__cloakRiskEnhanced = true') !== false;
$tests['enhanced_no_fatal'] = stripos((string) $enhOut, 'Fatal error') === false;

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