<?php
declare(strict_types=1);

// Separate cache-only read-only gate. It never invokes Cache, DB, or HTTP.
if (getenv('CDX_READ2_CACHE_PREFLIGHT') !== '1') {
    echo json_encode(['status' => 'default_deny',
        'cache_read_or_write' => false, 'database_connected' => false,
        'http_sent' => false, 'dml_sent' => false],
        JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit(78);
}
$stage = 'bootstrap';
set_exception_handler(static function (Throwable $error) use (&$stage): void {
    echo json_encode(['status' => 'redacted_error', 'stage' => $stage,
        'error_class' => get_class($error)], JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit(2);
});
set_error_handler(static function (int $severity): bool {
    if (!(error_reporting() & $severity)) return false;
    throw new ErrorException('redacted warning', 0, $severity);
});
$target = (string)getenv('CDX_READ2_TARGET');
$roots = [
    'A' => ['/private/tmp/zhct-http-ai-macos.zjaU8h', 18105],
    'B' => ['/private/tmp/zhct-http-ai-macos.x2CCZX', 18101],
    'C' => ['/tmp/zhct-ai-http-20260929.3XDj3w', 18102],
];
if (!isset($roots[$target])) throw new RuntimeException('Explicit target required');
[$root, $port] = $roots[$target];
$stage = 'private_source_and_path';
$realRoot = realpath($root);
$realCache = realpath($root . '/runtime/cache');
$approvedSha = 'ccf1c56eb4178f3eaad8775e26a27742b2cacf662b46fb058cbb91d23783b8c6';
if (!is_string($realRoot) || !is_string($realCache)
    || $realCache !== $realRoot . '/runtime/cache'
    || (((int)fileperms($realRoot) & 0077) !== 0)
    || !hash_equals($approvedSha, (string)hash_file('sha256',
        $root . '/config/cache.php'))
    || is_file($root . '/.env') || is_file($root . '/.env.poc')
    || getenv('CACHE_DRIVER') !== false || getenv('cache.driver') !== false) {
    throw new RuntimeException('Private file cache boundary mismatch');
}
$stage = 'http_worker_identity';
if ($target === 'C') {
    $cmdline = file_get_contents('/proc/53772/cmdline');
    $workerEnvironment = file_get_contents('/proc/53772/environ');
    if (!is_string($cmdline) || !is_string($workerEnvironment)
        || strpos($cmdline, $root . '/public') === false
        || strpos($cmdline, '127.0.0.1:' . $port) === false) {
        throw new RuntimeException('C worker mismatch');
    }
} else {
    $pidText = shell_exec('/usr/sbin/lsof -t -nP -iTCP:' . $port
        . ' -sTCP:LISTEN 2>/dev/null');
    $pids = array_values(array_filter(explode("\n", trim((string)$pidText)),
        static function (string $value): bool { return ctype_digit($value); }));
    if (count($pids) !== 1) throw new RuntimeException('A/B single worker required');
    $cmdline = shell_exec('/bin/ps eww -p ' . $pids[0] . ' -o command=');
    $alias = str_replace('/private/tmp/', '/tmp/', $root);
    if (!is_string($cmdline) || strpos($cmdline, '-S 127.0.0.1:' . $port) === false
        || (strpos($cmdline, $root . '/public') === false
            && strpos($cmdline, $alias . '/public') === false)) {
        throw new RuntimeException('A/B worker mismatch');
    }
    $workerEnvironment = $cmdline;
}
if (preg_match('/(?:^|[\s\x00])CACHE_DRIVER=/i', $workerEnvironment) === 1
    || preg_match('/(?:^|[\s\x00])cache\.driver=/i', $workerEnvironment) === 1) {
    throw new RuntimeException('HTTP cache override unproven');
}

$stage = 'effective_cli_config';
define('TP_ENV', 'poc');
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
require $root . '/vendor/autoload.php';
(new \think\App($root))->setEnvName('poc')->initialize();
$driver = \think\facade\Config::get('cache.default');
$path = \think\facade\Config::get('cache.stores.file.path');
$prefix = \think\facade\Config::get('cache.stores.file.prefix');
if (strtolower((string)$driver) !== 'file'
    || realpath((string)$path) !== $realCache
    || (string)$prefix !== '') {
    throw new RuntimeException('Effective CLI cache configuration mismatch');
}
echo json_encode(['status' => 'isolated_file_cache_config_pass',
    'target' => $target, 'http_worker_identity' => true,
    'same_root_config_sha' => true, 'effective_driver_file' => true,
    'root_local_cache_path' => true, 'cache_read_or_write' => false,
    'database_connected' => false, 'http_sent' => false, 'dml_sent' => false],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
