<?php
// [ 应用入口文件 ]
namespace think;

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/tx.php';
require __DIR__ . '/WxqqJump/WxqqJump.php';

$uri = $_SERVER['REQUEST_URI'] ?? '/';
$path = parse_url($uri, PHP_URL_PATH);

// /admin、/api、/go 走ThinkPHP路由
if (preg_match('#^/(admin|api)(/|$)#', $path) || preg_match('#^/go(/|$)#', $path)) {
    if (preg_match('#^/go(/|$)#', $path)) {
        $inspection = \tx_guard_inspect_request();
        if ($inspection['action'] === 'decoy') {
            \tx_guard_log('decoy', $inspection['reason']);
            \tx_guard_render_decoy();
            exit;
        }

        if ($inspection['action'] === 'wxqq_jump') {
            \tx_guard_log('wxqq_jump', $inspection['reason']);
            \render_wxqq_jump(\tx_guard_current_url());
            exit;
        }

        $params = $_GET;
        unset($params['s']); // 去掉 nginx try_files 注入的内部路由参数
        $queryString = http_build_query($params);
        $apiPath = '/api' . $path . ($queryString !== '' ? ('?' . $queryString) : '');
        header('Location: ' . $apiPath, true, 302);
        exit;
    }

    $http = (new App())->http;
    $response = $http->run();
    $response->send();
    $http->end($response);
    exit;
}

// 静态资源直接返回（由Nginx处理，这里是fallback）
if (preg_match('#\.(js|css|png|jpg|jpeg|gif|svg|ico|woff2?|ttf|eot|map)$#', $path)) {
    return false;
}

// 前台页面请求走防屏蔽分流
$inspection = \tx_guard_inspect_request();
if ($inspection['action'] === 'decoy') {
    \tx_guard_log('decoy', $inspection['reason']);
    \tx_guard_render_decoy();
    exit;
}

if ($inspection['action'] === 'wxqq_jump') {
    \tx_guard_log('wxqq_jump', $inspection['reason']);
    \render_wxqq_jump(\tx_guard_current_url());
    exit;
}

\tx_guard_render_spa(__DIR__ . '/index.html');
