<?php
declare(strict_types=1);

// Exact A-lane recovery after a single-worker HTTP-unknown barrier.
$case = (string)getenv('CDX_BATCH_RECOVER_CASE');
if (($argv[1] ?? '') !== '--recover'
    || !in_array($case, ['pure10', 'cross3'], true)
    || getenv('CDX_BATCH_RECOVER') !== ($case === 'cross3'
        ? 'ROOT_APPROVED_EXACT_A_CROSS3_TOKEN_RECOVERY_V1'
        : 'ROOT_APPROVED_EXACT_A_TOKEN_RECOVERY_V1')
    || getenv('CDX_BATCH_RECOVER_SHA') !== hash_file('sha256', __FILE__)) {
    echo json_encode(['status' => 'default_deny', 'cache_delete' => 0]), PHP_EOL;
    exit(78);
}
$stage = 'private_journal';
set_exception_handler(static function (Throwable $e) use (&$stage): void {
    echo json_encode(['status' => 'redacted_stop', 'stage' => $stage,
        'class' => get_class($e), 'reason_sha256' => hash('sha256', $e->getMessage())]), PHP_EOL;
    exit(2);
});
$path = (string)getenv('CDX_BATCH_JOURNAL');
$dir = dirname($path);
if (basename($path) !== 'journal.json'
    || strpos(basename($dir), 'cdx-ai-batch-') !== 0
    || !is_dir($dir) || is_link($dir) || !is_file($path) || is_link($path)
    || (((int)fileperms($dir) & 0077) !== 0)
    || (((int)fileperms($path) & 0077) !== 0)) {
    throw new RuntimeException('Private journal boundary changed');
}
$journal = json_decode((string)file_get_contents($path), true);
if (!is_array($journal) || ($journal['lane'] ?? '') !== 'A'
    || ($journal['state'] ?? '') !== 'request_started'
    || ($journal['current_route'] ?? '') !== ($case === 'cross3'
        ? 'POST /api/User/zhctInfo' : 'GET /api/health.Metric/trend')
    || ($journal['owner_sha12'] ?? '') !== 'ac65f0293982'
    || count($journal['routes'] ?? []) !== ($case === 'cross3' ? 3 : 10)
    || !preg_match('/^CDXBATCH[0-9A-F]{36}$/', (string)($journal['token'] ?? ''))
    || (int)($journal['expires_at'] ?? 0) - (int)($journal['created_at'] ?? 0) !== 300) {
    throw new RuntimeException('Exact interrupted batch state drift');
}
$stage = 'single_worker_barrier';
$listeners = trim((string)shell_exec('/usr/sbin/lsof -t -nP -iTCP:18105 -sTCP:LISTEN 2>/dev/null'));
$all = trim((string)shell_exec('/usr/sbin/lsof -nP -iTCP:18105 2>/dev/null'));
if ($listeners !== '13109' || count(array_filter(explode("\n", $all))) !== 2
    || strpos($all, '(LISTEN)') === false) {
    throw new RuntimeException('Single-worker idle barrier not proven');
}
$stage = 'isolated_cache';
$root = '/private/tmp/zhct-http-ai-macos.zjaU8h';
if (realpath($root) !== $root
    || (((int)fileperms($root) & 0077) !== 0)
    || realpath($root . '/runtime/cache') !== $root . '/runtime/cache'
    || hash_file('sha256', $root . '/config/cache.php')
        !== 'ccf1c56eb4178f3eaad8775e26a27742b2cacf662b46fb058cbb91d23783b8c6') {
    throw new RuntimeException('A private File cache drift');
}
define('TP_ENV', 'poc');
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
require $root . '/vendor/autoload.php';
(new \think\App($root))->setEnvName('poc')->initialize();
if (strtolower((string)\think\facade\Config::get('cache.default')) !== 'file'
    || realpath((string)\think\facade\Config::get('cache.stores.file.path'))
        !== $root . '/runtime/cache') {
    throw new RuntimeException('Effective cache boundary drift');
}
$stage = 'delete_exact_token';
$present = \think\facade\Cache::has($journal['token']);
if ($present && !\think\facade\Cache::delete($journal['token'])) {
    throw new RuntimeException('Exact token delete uncertain');
}
$journal['state'] = 'deleted_needs_zero';
unset($journal['current_route']);
$encoded = json_encode($journal, JSON_UNESCAPED_SLASHES);
$temp = $path . '.tmp';
if (!is_string($encoded)
    || file_put_contents($temp, $encoded, LOCK_EX) !== strlen($encoded)
    || !chmod($temp, 0600) || !rename($temp, $path)) {
    throw new RuntimeException('Recovery journal update failed');
}
echo json_encode(['status' => 'exact_a_token_recovered',
    'present_before' => $present, 'business_http' => 0, 'business_dml' => 0]), PHP_EOL;
