<?php

use XiaoPHP\System\Config\Route;
use XiaoPHP\System\Logs;
use XiaoPHP\System\Helper;
use XiaoPHP\System\Middleware;
use XiaoPHP\System\Container;

// ========== 初始化 ==========
$container = Container::getInstance();
$container->make(Middleware::class)->check();

// ========== 解析请求 ==========
$path = trim($_SERVER["REQUEST_URI"], "/");
$path = strtok($path, "?");
$pathLower = strtolower($path);
$segments = explode("/", $pathLower);

// ========== 精确路由匹配（优先） ==========
$route = Route::find("/" . $pathLower, $_SERVER['REQUEST_METHOD'] ?? 'GET');
if ($route) {
    dispatchRoute($container, $route);
    exit(0);
}

// ========== 静态资源（含点的文件） ==========
if (strpos($path, '.') !== false) {
    serveStatic($path);
    exit(0);
}

// ========== 自动路由 ==========
dispatchAuto($container, $segments);
exit(0);

// ========== 核心函数 ==========

/**
 * 提供静态文件服务
 */
function serveStatic(string $path): void
{
    $webRoot = __DIR__ . "/../Resources";
    $webRootReal = realpath($webRoot);
    $filePath = realpath($webRoot . "/" . $path);
    
    // 安全校验：必须在 Resources 目录内（含目录分隔符边界，防目录穿越）
    if (!$webRootReal || !$filePath || strpos($filePath, $webRootReal . DIRECTORY_SEPARATOR) !== 0 || !is_file($filePath)) {
        Error(404, "文件不存在");
        return;
    }
    
    // 下载头（文件名过滤引号/换行，防 Header 注入）
    $fileName = preg_replace('/[\r\n"]/', '', basename($path)) ?: 'download';
    header('Content-Type: ' . (mime_content_type($filePath) ?: 'application/octet-stream'));
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    header('Content-Length: ' . filesize($filePath));
    header('Accept-Ranges: bytes');
    
    // 输出文件
    readfile($filePath);
    Container::getInstance()->make(Logs::class)->logs(0, 200);
}

/**
 * 分发路由（修复请求方法验证）
 */
function dispatchRoute(Container $container, string $route): void
{
    [$method, $classPath, $namespace] = explode(":", $route);
    
    // 修复：正确的请求方法验证
    $requestMethod = $_SERVER['REQUEST_METHOD'] ?? 'GET';
    if (strtoupper($requestMethod) !== strtoupper($method)) {
        $container->make(Logs::class)->logs(1, 405);
        Error(405, "请求方法不允许");
        return;
    }
    
    [$controller, $action] = explode("/", $classPath) + [1 => "Main"];
    // 兼容空方法段（如 Route::add 传 "Login/"）
    if ($action === '') {
        $action = 'Main';
    }
    $file = __DIR__ . "/../{$namespace}/{$controller}.php";
    
    // 查找文件（不区分大小写）
    $file = Helper::findFileCaseInsensitive(dirname($file), basename($file)) ?: $file;
    
    if (!is_file($file)) {
        $container->make(Logs::class)->logs(1, 404);
        Error(404, "控制器不存在");
        return;
    }
    
    Helper::loadSiblingControllers($file);
    require_once $file;
    
    // 获取真实控制器名
    $realController = pathinfo($file, PATHINFO_FILENAME);
    if (!class_exists($realController)) {
        if (!class_exists($controller)) {
            $container->make(Logs::class)->logs(1, 404);
            Error(404, "控制器类不存在");
            return;
        }
        $realController = $controller;
    }
    
    $instance = $container->make($realController);
    $realAction = Helper::findMethodCaseInsensitive($instance, $action);
    
    if (!$realAction) {
        $container->make(Logs::class)->logs(1, 404);
        Error(404, "方法不存在");
        return;
    }
    
    echo $instance->{$realAction}();
    $container->make(Logs::class)->logs(0, 200);
}


function dispatchAuto(Container $container, array $segments): void
{
    // 处理根路径（未注册 / 路由时的兜底：进入 Index 控制器）
    if (empty($segments) || empty($segments[0])) {
        $app = 'Index';
        $controller = 'Index';
        $action = 'Main';
    } else {
        $app = preg_replace("/[^a-zA-Z0-9_-]/", "", $segments[0]);
        $controller = preg_replace("/[^a-zA-Z0-9_-]/", "", $segments[1] ?? 'Main');
        $action = preg_replace("/[^a-zA-Z0-9_-]/", "", $segments[2] ?? 'Main');
        // 兼容斜杠结尾 URL（如 /oauth/Authorize/）：空段回退 Main（2.1.0 行为，2.1.3 回归修复）
        if ($controller === '') {
            $controller = 'Main';
        }
        if ($action === '') {
            $action = 'Main';
        }
    }
    
    // 查找应用目录
    $appDir = Helper::findDirCaseInsensitive(__DIR__ . "/../App", $app);
    if (!$appDir) {
        $container->make(Logs::class)->logs(1, 404);
        Error(404, "应用不存在");
        return;
    }
    
    // 查找控制器
    $file = Helper::findFileCaseInsensitive($appDir . "/Controller", $controller . ".php");
    if (!$file) {
        $container->make(Logs::class)->logs(1, 404);
        Error(404, "控制器不存在");
        return;
    }
    
    $realController = pathinfo($file, PATHINFO_FILENAME);
    Helper::loadSiblingControllers($file);
    require_once $file;
    
    if (!class_exists($realController)) {
        $container->make(Logs::class)->logs(1, 404);
        Error(404, "控制器类不存在");
        return;
    }
    
    $instance = $container->make($realController);
    $realAction = Helper::findMethodCaseInsensitive($instance, $action);
    
    if (!$realAction) {
        $container->make(Logs::class)->logs(1, 404);
        Error(404, "方法不存在");
        return;
    }
    
    echo $instance->{$realAction}();        
    $container->make(Logs::class)->logs(0, 200);
}
