<?php
// CLI only: do not publish this validator into the web root.
if (PHP_SAPI !== 'cli' || $argc !== 3) {
    exit(2);
}
function stopDeploy($message) {
    fwrite(STDERR, "重庆配置校验失败：" . $message . "\n");
    exit(1);
}
$project = rtrim($argv[1], '/');
$package = rtrim($argv[2], '/');
foreach ([$project . '/env.php', $package . '/public/dist/index.html'] as $path) {
    if (!is_file($path) || is_link($path)) {
        stopDeploy('入口文件缺失或为软链接，停止发布');
    }
}
require $project . '/env.php';
if (!defined('TP_ENV') || TP_ENV !== 'local') {
    stopDeploy('现场环境不是 local，先恢复已确认的重庆配置，不得保留错误环境继续升级');
}
$business = defined('BUSINESS') ? BUSINESS : '';
if (!in_array($business, ['', 'BUSINESS_VALUE', 'zhct_cqhw'], true)) {
    stopDeploy('现场 BUSINESS 不属于重庆，停止发布');
}
$suffix = ($business !== '' && $business !== 'BUSINESS_VALUE') ? '/' . $business : '';
$configDir = $project . '/application/config/local' . $suffix;
foreach (['config.php', 'database.php'] as $name) {
    if (!is_file($configDir . '/' . $name) || is_link($configDir . '/' . $name)) {
        stopDeploy('现场 local 配置缺失或为软链接');
    }
}
// Isolate the two includes: deployed config files commonly reuse $config.
$load = function ($path) { return require $path; };
$config = $load($configDir . '/config.php');
$database = $load($configDir . '/database.php');
if (!is_array($config) || !is_array($database)) {
    stopDeploy('配置必须返回数组');
}
if (($config['business'] ?? '') !== 'zhct_cqhw') {
    stopDeploy('主项目 business 不是 zhct_cqhw');
}
$loopback = ['127.0.0.1', 'localhost', '::1'];
if (!in_array($config['redis']['host'] ?? '', $loopback, true)
    || (int)($config['redis']['port'] ?? 0) !== 6379) {
    stopDeploy('Redis 不是已确认的本机 6379 配置');
}
if (!in_array($database['hostname'] ?? '', $loopback, true)
    || ($database['database'] ?? '') !== 'zhct_cqhw') {
    stopDeploy('数据库不属于本机 zhct_cqhw');
}
$html = file_get_contents($package . '/public/dist/index.html');
if (!preg_match('/\b(?:var|let|const)\s+BUSINESS\s*=\s*[\'"]zhct_cqhw[\'"]\s*;/', $html)) {
    stopDeploy('包内 PC 前端不是重庆构建，不能直接发布其他项目的包');
}
echo "重庆配置校验通过：local / zhct_cqhw / 本机 Redis 与数据库\n";
