<?php
/**
 * AI 单页站群系统 - 入口
 * 路由：/后台路径 => 管理后台；其余 => 前台站点渲染
 */
define('DY_START', microtime(true));
require __DIR__ . '/app/bootstrap.php';

$uri  = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$path = parse_url($uri, PHP_URL_PATH);
$path = rawurldecode((string)$path); // 中文文件名会被浏览器转成百分号编码，先解码才能命中本地文件
if (strpos($path, '..') !== false) { http_response_code(400); exit('bad request'); } // 防目录穿越
$path = trim($path, '/');
$serve = $path;
if ($path !== '' && !is_file(__DIR__ . '/' . $path) && preg_match('/\.(png|jpe?g|gif|webp)$/i', $path)) {
    // 图片 404 兜底：文件被改名/移动时按文件名数字串匹配回 assets/images 真实文件
    $rescued = DY_Core_ImgRescue::resolve('/' . $path);
    if ($rescued !== null && is_file(__DIR__ . '/' . $rescued)) $serve = $rescued;
}
if ($serve !== '' && is_file(__DIR__ . '/' . $serve) && strpos($serve, 'app/') !== 0 && strpos($serve, 'data/') !== 0 && strpos($serve, 'storage/') !== 0) {
    // 静态资源直出（伪静态转发进来时由 PHP 自己吐文件，避免空响应）
    $mime = array(
        'css' => 'text/css; charset=UTF-8', 'js' => 'application/javascript; charset=UTF-8',
        'png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif',
        'svg' => 'image/svg+xml', 'ico' => 'image/x-icon', 'woff' => 'font/woff', 'woff2' => 'font/woff2',
        'ttf' => 'font/ttf', 'txt' => 'text/plain; charset=UTF-8', 'map' => 'application/json',
    );
    $ext = strtolower(pathinfo($serve, PATHINFO_EXTENSION));
    header('Content-Type: ' . (isset($mime[$ext]) ? $mime[$ext] : 'application/octet-stream'));
    header('Content-Length: ' . filesize(__DIR__ . '/' . $serve));
    header('Cache-Control: public, max-age=3600');
    readfile(__DIR__ . '/' . $serve);
    exit;
}

$adminPath = DY_Setting::get('admin_path', 'admin');
if (strtolower($path) === strtolower($adminPath) || strpos(strtolower($path), strtolower($adminPath) . '/') === 0) {
    $sub = trim(substr($path . '/', strlen($adminPath)), '/');
    (new DY_AdminController($sub))->dispatch();
} else {
    (new DY_FrontController($path))->run();
}

DY_LogModel::tickWorkerAuto(); // 有任务自动触发生成（响应后执行）
