<?php
declare(strict_types=1);

// Test-only PHP built-in-server router. Exactly three read routes plus boundary.
namespace think;

define('TP_ENV', 'poc');
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
$uri = (string)($_SERVER['REQUEST_URI'] ?? '');
$method = (string)($_SERVER['REQUEST_METHOD'] ?? '');
$allowed = [
    '/api/user.score/weightRank?limit=50',
    '/api/user.score/dietRank?limit=50',
    '/api/user.score/courseRank?limit=50',
];
if ($method !== 'GET' || (int)($_SERVER['CONTENT_LENGTH'] ?? 0) !== 0
    || ($uri !== '/__score_rank_boundary' && !in_array($uri, $allowed, true))) {
    http_response_code(403);
    return;
}
if ($uri !== '/__score_rank_boundary'
    && ((string)($_SERVER['HTTP_PLATFORM'] ?? '') !== 'MP-WEIXIN'
        || (string)($_SERVER['HTTP_VERSION'] ?? '') !== '2.0.51'
        || (string)($_SERVER['HTTP_ENV_VERSION'] ?? '') !== 'develop'
        || (string)($_SERVER['HTTP_ACCESS_TOKEN'] ?? '') !== ''
        || (string)($_SERVER['HTTP_ENTERPRISE_NO'] ?? '') !== '')) {
    http_response_code(403);
    return;
}
require __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../vendor/topthink/framework/src/helper.php';
if (getenv('POC_EXTERNAL_STUBS') !== '1') {
    http_response_code(503);
    return;
}
require __DIR__ . '/../external_stubs.php';
$app = (new App(dirname(__DIR__)))->setEnvName('poc');

$rawUuid = (string)getenv('PHP_ZGYH_DEPARTMENT_UUID');
$approvedSha = (string)getenv('CDX_SCORE_DEPT_SHA');
if ($rawUuid === '' || !preg_match('/^[a-zA-Z0-9-]{32,64}$/D', $rawUuid)
    || !preg_match('/^[a-f0-9]{64}$/D', $approvedSha)
    || !hash_equals($approvedSha, hash('sha256', $rawUuid))) {
    http_response_code(503);
    return;
}

// This invokes the same ThinkPHP helper used by Score.php. A mismatch stops
// before any business controller or query. Never return the raw UUID.
try {
    $frameworkUuid = (string)env('zgyh.department_uuid');
} catch (\Throwable $error) {
    http_response_code(503);
    return;
}
if (!hash_equals($rawUuid, $frameworkUuid)) {
    http_response_code(503);
    return;
}

if ($method === 'GET' && $uri === '/__score_rank_boundary') {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'isolated-score-rank-boundary',
        'department_env_sha256' => $approvedSha,
        'framework_env_matches_process' => true,
        'external_stubs' => class_exists(\app\common\Serve::class, false)
            && class_exists(\app\common\UserApi::class, false)],
        JSON_UNESCAPED_SLASHES);
    return;
}
$http = $app->http;
$response = $http->run();
$response->send();
$http->end($response);
