#!/usr/bin/env php
<?php
/**
 * CloakJudgmentCache / RiskSecondaryCache 回归（CLI JSON）
 */
if (PHP_SAPI !== 'cli') {
    exit(1);
}

$root = dirname(__DIR__);
require_once $root . '/cong.php';
require_once $root . '/lib/Cloak/ClientIpResolver.php';
require_once $root . '/lib/Cloak/RiskSecondaryGate.php';
require_once $root . '/lib/Cloak/CloakJudgmentCache.php';
require_once $root . '/lib/Cloak/RiskSecondaryCache.php';

if (!defined('CLOAK_RISK_NUMBER')) {
    define('CLOAK_RISK_NUMBER', 51);
}
if (!defined('COSTM_IP_SCORE')) {
    define('COSTM_IP_SCORE', 'test_campaign');
}

$_SESSION = [];
$tests    = [];

CloakJudgmentCache::storeFromByApiRisk([
    'ip'      => '203.0.113.10',
    'country' => 'US',
    'result'  => 'true',
    'reason'  => '',
    'fp_url'  => 'https://fp.example/a',
]);
$hit = CloakJudgmentCache::getFinal('203.0.113.10');
$tests['same_ip_final_hit'] = is_array($hit) && ($hit['result'] ?? '') === 'true' && ($hit['stage'] ?? '') === CloakJudgmentCache::STAGE_FINAL;

if (is_array($hit)) {
    CloakJudgmentCache::applyToSession($hit);
}
$tests['apply_session_final'] = ($_SESSION['visit_to_3'] ?? '') == 3 && ($_SESSION['check_result'] ?? '') === 'true';

$hitNewIp = CloakJudgmentCache::get('198.51.100.5');
$tests['ip_change_still_valid'] = is_array($hitNewIp) && ($hitNewIp['result'] ?? '') === 'true';
$tests['ip_change_updates_ip_field'] = ($hitNewIp['ip'] ?? '') === '198.51.100.5';
$tests['ip_change_keeps_session_key'] = !empty($_SESSION[CloakJudgmentCache::SESSION_KEY]);

$partialOnly = CloakJudgmentCache::getFinal('198.51.100.5');
$tests['risk_cache_get_skips_partial'] = true;
CloakJudgmentCache::clear();
CloakJudgmentCache::storeFromByApi([
    'ip'      => '203.0.113.10',
    'country' => 'US',
    'result'  => 'true',
    'reason'  => 'api ok',
]);
$tests['byapi_stage_is_partial'] = CloakJudgmentCache::isPartial();
$tests['risk_cache_get_skips_partial'] = RiskSecondaryCache::get('203.0.113.10') === null;

CloakJudgmentCache::storeFromByApiRisk([
    'ip'      => '203.0.113.10',
    'country' => 'US',
    'result'  => 'false',
    'reason'  => 'deny',
    'fp_url'  => 'https://zp.example/',
]);
$apiHit = CloakJudgmentCache::getFinal('203.0.113.10');
$api = is_array($apiHit) ? CloakJudgmentCache::toApiResponse($apiHit) : ['result' => true, 'reason' => ''];
$tests['to_api_response'] = $api['result'] === false && $api['reason'] === CloakJudgmentCache::hitReason();

$_SESSION[CloakJudgmentCache::SESSION_KEY]['risk_number'] = -1;
$tests['risk_number_change_invalidates'] = CloakJudgmentCache::getFinal('203.0.113.10') === null;

CloakJudgmentCache::clear();
$tests['clear'] = !CloakJudgmentCache::hasSession();

$originOk = false;
$_SERVER['HTTP_HOST'] = 'cloak.example.com';
$_SERVER['HTTP_ORIGIN'] = 'https://www.example.com';
require_once $root . '/lib/Cloak/CloakSession.php';
$ref = new ReflectionClass('CloakFcheckCors');
$method = $ref->getMethod('isAllowedOrigin');
$method->setAccessible(true);
$originOk = (bool) $method->invoke(null, 'https://www.example.com');
$tests['cors_sibling_subdomain'] = $originOk;

$badOrigin = !(bool) $method->invoke(null, 'https://evil.other.com');
$tests['cors_reject_foreign'] = $badOrigin;

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