<?php
/**
 * 白名单 / 正品模式早期快速路径验证
 * 输出 JSON：{ok, checks: [...]}
 */
$root = dirname(__DIR__);
require_once $root . '/cong.php';
require_once $root . '/lib/bootstrap.php';

$checks = [];

function check_gate($name, $cond, $detail = '')
{
    global $checks;
    $checks[] = ['name' => $name, 'ok' => (bool) $cond, 'detail' => $detail];
}

function run_pipeline_fixture($root, $fixtureName)
{
    $fixture = $root . '/tools/fixtures/' . $fixtureName;
    $cmd     = escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($root . '/tools/run_pipeline_fixture.php')
        . ' ' . escapeshellarg($fixture) . ' 2>&1';
    exec($cmd, $out, $code);
    $json = json_decode(implode("\n", $out), true);

    return is_array($json) ? $json : ['error' => implode("\n", $out), 'code' => $code];
}

// WhitelistGate（独立子进程，避免常量冲突）
$gateCmd = escapeshellarg(PHP_BINARY) . ' -r ' . escapeshellarg(
    'define("SHOW_SITE_IP","8.8.8.8");define("WHITE_PARAMS","token=abc");define("WHITELIST_GROUP_ID",0);'
    . 'require ' . var_export($root . '/lib/bootstrap.php', true) . ';'
    . '$_GET=["token"=>"abc"];'
    . 'echo json_encode(["ip"=>WhitelistGate::matchesWhitelistIp("8.8.8.8"),"param"=>WhitelistGate::matchesWhitelistParams()]);'
);
$gateJson = json_decode((string) shell_exec($gateCmd), true);
check_gate('WhitelistGate IP/参数', ($gateJson['ip'] ?? false) && ($gateJson['param'] ?? false));

$zp = run_pipeline_fixture($root, 'regression_zp.php');
check_gate(
    'zp 模式仅记录国家并判定 false',
    ($zp['mode'] ?? '') === 'zp'
    && ($zp['result'] ?? null) === 'false'
    && ($zp['reason'] ?? '') === '正品模式',
    json_encode($zp, JSON_UNESCAPED_UNICODE)
);

$wl = run_pipeline_fixture($root, 'regression_whitelist_fast.php');
check_gate(
    '白名单快速路径判定 true',
    ($wl['result'] ?? null) === 'true',
    json_encode($wl, JSON_UNESCAPED_UNICODE)
);

$zpWl = run_pipeline_fixture($root, 'regression_zp_whitelist.php');
check_gate(
    'zp 模式下白名单仍判定 true',
    ($zpWl['mode'] ?? '') === 'zp'
    && ($zpWl['result'] ?? null) === 'true',
    json_encode($zpWl, JSON_UNESCAPED_UNICODE)
);

$simOut = shell_exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($root . '/tools/verify_simulation_zp_whitelist_route.php') . ' 2>/dev/null');
$simJson = null;
if (preg_match('/\{.*\}\s*$/s', (string) $simOut, $m)) {
    $simJson = json_decode($m[0], true);
}
check_gate(
    'SimulationRouteResolver zp+白名单走真实页',
    ($simJson['ok'] ?? false) === true,
    (string) $simOut
);

$ok = true;
foreach ($checks as $c) {
    if (!$c['ok']) {
        $ok = false;
        break;
    }
}

echo json_encode(['ok' => $ok, 'checks' => $checks], JSON_UNESCAPED_UNICODE);
