<?php
/**
 * 流量判定主流水线
 *
 * 阶段顺序（不可调换）：
 * 1. Session 快速路径 → 2. GeoIP 国家 → 3. 黑白名单 → 4. 广告来源 → 5. 临时链接 → 6. API/指纹
 */
class CheckPipeline
{
    /**
     * 在调用方（ip_check 顶层）作用域执行完整判定链。
     * 依赖全局：$v_info, $config_name, $__cloak_debug_on, $reason
     *
     * @return void
     */
    public static function run()
    {
        global $v_info, $config_name, $__cloak_debug_on, $__cloak_debug_started, $reason;

        if (!isset($reason)) {
            $reason = '';
        }

        CloakPipelineTimer::init();

        CloakPipelineTimer::stage('Session快速路径');
        if (self::resolveSessionFastPath()) {
            include __DIR__ . '/stages/resolve_session_fast_path_hit.inc.php';
            CloakPipelineTimer::finish();
            return;
        }

        if ($__cloak_debug_on) {
            cloak_dbg_step(__LINE__, 'Session 快速路径', 'skip', '未命中缓存，进入完整判定流程（DEBUG 已重置 visit_to_*）');
        }

        CloakPipelineTimer::stage('GeoIP国家判定');
        include __DIR__ . '/stages/check_country_geoip.inc.php';
        if (!empty($_SESSION['check_result'])) {
            CloakPipelineTimer::finish();
            return;
        }

        CloakPipelineTimer::stage('黑白名单');
        include __DIR__ . '/stages/apply_whitelist_blacklist.inc.php';
        CloakPipelineTimer::stage('广告来源限制');
        include __DIR__ . '/stages/run_ad_source_guard.inc.php';
        CloakPipelineTimer::stage('临时链接参数');
        include __DIR__ . '/stages/check_url_args_timeout.inc.php';
        include __DIR__ . '/stages/run_main_api_fingerprint.inc.php';
        CloakPipelineTimer::finish();
    }

    /**
     * 是否命中 session 缓存结果（true = 跳过完整判定）
     *
     * @return bool
     */
    public static function resolveSessionFastPath()
    {
        global $__cloak_debug_on;

        return (
            !$__cloak_debug_on
            && SHOW_SITE_MODE_SWITCH === 'ip_check'
            && isset($_SESSION['check_result'])
            && ($_SESSION['check_result'] === 'true' || $_SESSION['check_result'] === 'false')
        );
    }
}
