#!/usr/bin/env php
<?php
/**
 * Visit 生命周期与 reason 规范化回归（CLI JSON）
 */
if (PHP_SAPI !== 'cli') {
    exit(1);
}

$root = dirname(__DIR__);
require_once $root . '/cong.php';
require_once $root . '/lib/Cloak/ReasonHelper.php';
require_once $root . '/lib/Cloak/VisitorVisitContext.php';
require_once $root . '/lib/Cloak/RiskSecondarySession.php';
require_once $root . '/lib/Cloak/CloakJudgmentCache.php';
require_once $root . '/lib/Cloak/RiskSecondaryCache.php';

$tests = [];

// reason 规范化
$tests['true_reason_empty'] = cloak_normalize_log_reason('true', '二次风控缓存命中') === '';
$tests['cache_false_reason'] = cloak_cache_hit_log_reason('false') === '缓存';
$tests['cache_hit_reason'] = CloakJudgmentCache::hitReason() === '缓存';
$tests['false_reason_required'] = cloak_normalize_log_reason('false', '') !== '';
$tests['wait_default_reason'] = cloak_normalize_log_reason('wait', '') === '二次风控检测中';
$tests['finalize_true_empty'] = cloak_finalize_reason('缓存', 'true') === '';

// 新 visit / 续步判定
$_SESSION = [];
$_SERVER['SCRIPT_NAME'] = '/ip_check.php';
unset($_GET['time'], $_SERVER['HTTP_SEC_FETCH_MODE']);
$tests['first_load_new_visit'] = VisitorVisitContext::isNewVisit() && !VisitorVisitContext::isContinuation();

VisitorVisitContext::bindLogId(1001);
VisitorVisitContext::markVisitActive();
$tests['wait_bound_not_new'] = !VisitorVisitContext::isNewVisit() && VisitorVisitContext::shouldPersistAsUpdate();

$_GET['time'] = '123';
$tests['time_param_continuation'] = VisitorVisitContext::isContinuation();
unset($_GET['time']);

$_SERVER['HTTP_SEC_FETCH_MODE'] = 'navigate';
VisitorVisitContext::evaluateAtEntry();
$tests['refresh_clears_visit'] = VisitorVisitContext::currentLogId() === 0 && VisitorVisitContext::isNewVisit();
unset($_SERVER['HTTP_SEC_FETCH_MODE']);

// f_check 续步
$_SESSION = [];
VisitorVisitContext::bindLogId(2002);
$_SERVER['SCRIPT_NAME'] = '/f_check.php';
$tests['fcheck_is_continuation'] = VisitorVisitContext::isContinuation();
$_SERVER['SCRIPT_NAME'] = '/ip_check.php';

// finalize 后新 visit
VisitorVisitContext::finalizeVisit('true');
$tests['after_finalize_new_visit'] = VisitorVisitContext::isNewVisit();

// RiskSecondarySession skip 写库
$_SESSION['visit_to_3'] = 3;
VisitorVisitContext::bindLogId(3003);
VisitorVisitContext::finalizeVisit('true');
$tests['skip_fp_after_finalize'] = RiskSecondarySession::shouldSkipFpPageLog();

// 缓存命中 reason 不落库为 true 文案
$cached = ['result' => 'true', 'reason' => 'ok', 'fp_url' => 'https://fp/a'];
$api = RiskSecondaryCache::toApiResponse($cached);
$normalized = cloak_normalize_log_reason($api['result'] ? 'true' : 'false', $api['reason']);
$tests['cache_hit_true_reason_empty'] = $normalized === '';

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