<?php
require_once __DIR__ . '/../WhitelistGate.php';
require_once __DIR__ . '/../CloakJudgmentCache.php';
require_once __DIR__ . '/../RiskSecondaryGate.php';

/**
 * 流量判定主流水线
 *
 * 优先级（高 → 低）：
 * 1. 白名单链接参数 WHITE_PARAMS
 * 2. 白名单 IP
 * 3. 黑名单
 * 4. 屏蔽模式：安全页(zp) / 真实页(fp)
 * 5. 正常屏蔽(ip_check)：Session 最终缓存 > 阶段缓存续跑 > 完整判定
 */
class CheckPipeline
{
    /**
     * @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('白名单链接参数');
        if (self::resolveWhitelistParamsFastPath()) {
            include __DIR__ . '/stages/resolve_whitelist_fast_path_hit.inc.php';
            CloakPipelineTimer::finish();
            return;
        }

        CloakPipelineTimer::stage('白名单IP');
        if (self::resolveWhitelistIpFastPath()) {
            include __DIR__ . '/stages/resolve_whitelist_fast_path_hit.inc.php';
            CloakPipelineTimer::finish();
            return;
        }

        CloakPipelineTimer::stage('黑名单');
        if (self::resolveBlacklistFastPath()) {
            include __DIR__ . '/stages/resolve_blacklist_fast_path_hit.inc.php';
            CloakPipelineTimer::finish();
            return;
        }

        CloakPipelineTimer::stage('安全页模式');
        if (self::resolveZpFastPath()) {
            include __DIR__ . '/stages/resolve_zp_fast_path_hit.inc.php';
            CloakPipelineTimer::finish();
            return;
        }

        CloakPipelineTimer::stage('真实页模式');
        if (self::resolveFpFastPath()) {
            include __DIR__ . '/stages/resolve_fp_fast_path_hit.inc.php';
            CloakPipelineTimer::finish();
            return;
        }

        CloakPipelineTimer::stage('客户端缓存快速路径');
        if (self::resolveClientCacheFastPath()) {
            include __DIR__ . '/stages/resolve_session_fast_path_hit.inc.php';
            CloakPipelineTimer::finish();
            return;
        }

        CloakPipelineTimer::stage('客户端阶段缓存续跑');
        if (self::resolvePartialCacheResume()) {
            include __DIR__ . '/stages/run_main_api_fingerprint.inc.php';
            CloakPipelineTimer::finish();
            return;
        }

        if ($__cloak_debug_on) {
            cloak_dbg_step(__LINE__, '完整判定', 'info', '未命中早期快速路径，进入完整判定');
        }

        CloakPipelineTimer::stage('黑白名单');
        include __DIR__ . '/stages/apply_whitelist_blacklist.inc.php';
        if (!empty($_SESSION['check_result'])) {
            CloakPipelineTimer::finish();
            return;
        }

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

        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();
    }

    public static function resolveWhitelistParamsFastPath()
    {
        return WhitelistGate::matchesWhitelistParams();
    }

    public static function resolveWhitelistIpFastPath()
    {
        global $v_info;

        if (WhitelistGate::matchesWhitelistParams()) {
            return false;
        }

        return WhitelistGate::matchesWhitelistIp(WhitelistGate::resolveVisitorIp($v_info));
    }

    public static function resolveBlacklistFastPath()
    {
        global $v_info;

        if (!defined('BLACKLIST_GROUP_ID') || (int) BLACKLIST_GROUP_ID <= 0) {
            return false;
        }
        $blEntries = ip_group_list_addresses((int) BLACKLIST_GROUP_ID);

        return ip_visitor_in_blacklist_entries($v_info->v_ip, $blEntries);
    }

    public static function resolveClientCacheFastPath()
    {
        global $__cloak_debug_on, $v_info;

        if ($__cloak_debug_on || SHOW_SITE_MODE_SWITCH !== 'ip_check') {
            return false;
        }

        $cached = CloakJudgmentCache::getFinal();
        if ($cached === null) {
            return false;
        }

        CloakJudgmentCache::applyToSession($cached);
        CloakJudgmentCache::applyToVisitorInfo($v_info, $cached);

        if ($__cloak_debug_on) {
            CloakDebugPage::setFlag('session_cached', true);
        }

        return true;
    }

    public static function resolvePartialCacheResume()
    {
        global $__cloak_debug_on, $v_info, $reason;

        if ($__cloak_debug_on || SHOW_SITE_MODE_SWITCH !== 'ip_check') {
            return false;
        }

        $cached = CloakJudgmentCache::get();
        if (!CloakJudgmentCache::isPartial($cached)) {
            return false;
        }

        CloakJudgmentCache::applyToSession($cached);
        CloakJudgmentCache::applyToVisitorInfo($v_info, $cached);
        $_SESSION['visit_to_2'] = '2';

        if ($reason === '') {
            $reason = 'Session byApi阶段缓存：待二次风控';
        }

        if ($__cloak_debug_on) {
            cloak_dbg_step(__LINE__, '客户端阶段缓存续跑', 'pass', '命中 byapi 阶段缓存，跳过 GeoIP/Guard/byApi');
        }

        return true;
    }

    /**
     * @deprecated
     */
    public static function resolveSessionFastPath()
    {
        return self::resolveClientCacheFastPath();
    }

    /**
     * @deprecated 使用 resolveWhitelistParamsFastPath / resolveWhitelistIpFastPath
     */
    public static function resolveWhitelistFastPath()
    {
        return self::resolveWhitelistParamsFastPath() || self::resolveWhitelistIpFastPath();
    }

    public static function resolveZpFastPath()
    {
        return defined('SHOW_SITE_MODE_SWITCH') && SHOW_SITE_MODE_SWITCH === 'zp';
    }

    public static function resolveFpFastPath()
    {
        return defined('SHOW_SITE_MODE_SWITCH') && SHOW_SITE_MODE_SWITCH === 'fp';
    }
}
