<?php

declare(strict_types=1);

// Bounded, read-only Bank/topDepartments C verifier. Never print worker env,
// database credentials, department names/UUIDs, or HTTP response bodies.
set_exception_handler(static function (Throwable $error): void {
    echo json_encode(['status' => 'halt', 'class' => get_class($error),
        'message_sha256' => hash('sha256', $error->getMessage())]), PHP_EOL;
    exit(3);
});

$mode = (string)($argv[1] ?? '');
if (!in_array($mode, ['--preflight', '--execute'], true) || count($argv) !== 2
    || ($mode === '--execute'
        && (string)getenv('CDX_BANK_C_APPROVED') !== 'ONE_READ_ONLY_HTTP_V1')) {
    echo json_encode(['status' => 'default_deny', 'business_http' => 0]), PHP_EOL;
    exit(78);
}

$workerPid = 53772;
$command = @file_get_contents('/proc/' . $workerPid . '/cmdline');
$rawEnvironment = @file_get_contents('/proc/' . $workerPid . '/environ');
if (!is_string($command) || !is_string($rawEnvironment)
    || strpos($command, '127.0.0.1:18102') === false
    || strpos($command, '/tmp/zhct-ai-http-20260929.3XDj3w/public') === false) {
    throw new RuntimeException('fixed C isolated AI worker changed');
}

$environment = [];
foreach (explode("\0", $rawEnvironment) as $entry) {
    $separator = strpos($entry, '=');
    if ($separator !== false) {
        $environment[substr($entry, 0, $separator)] = substr($entry, $separator + 1);
    }
}
foreach (['POC_DIALECT' => 'dm', 'POC_EXTERNAL_STUBS' => '1',
    'POC_HOST' => '127.0.0.1', 'POC_PORT' => '5237',
    'POC_SCHEMA' => 'ZHCT_APP', 'POC_AI_HOST' => '127.0.0.1',
    'POC_AI_PORT' => '5238', 'POC_AI_SCHEMA' => 'AIZHCT_APP'] as $key => $expected) {
    if (($environment[$key] ?? '') !== $expected) {
        throw new RuntimeException('C nonproduction database or stub boundary changed');
    }
}
$servicePath = (string)($environment['DM_SVC_PATH'] ?? '');
if ($servicePath === '' || !is_file($servicePath . '/dm_svc.conf')
    || strpos((string)file_get_contents($servicePath . '/dm_svc.conf'),
        'CHAR_CODE=(PG_UTF8)') === false) {
    throw new RuntimeException('C DM client configuration changed');
}

$runner = '/tmp/cdx-bank-topdept-20261003/verify_bank_top_departments.disabled.php';
$runnerSha = '51184c01a5e0f39dfe2d1c20d9cf249073036784a598f756f4d3fb810c3bd9f3';
if (is_link($runner) || !is_file($runner)
    || (fileperms(dirname($runner)) & 0777) !== 0700
    || (fileperms($runner) & 0777) !== 0600
    || !hash_equals($runnerSha, hash_file('sha256', $runner))) {
    throw new RuntimeException('private fixed runner changed');
}

if ($mode === '--execute') {
    $environment['CDX_BANK_TOPDEPT_APPROVED'] = 'BANK_TOPDEPARTMENTS_READ_V1';
    $environment['CDX_BANK_TOPDEPT_LANE'] = 'C';
    $environment['CDX_BANK_TOPDEPT_SCRIPT_SHA'] = $runnerSha;
    $environment['CDX_BANK_AB_PARITY_VERIFIED'] = '1';
    $environment['CDX_BANK_EXPECT_B_RESPONSE_SHA'] =
        '3e3f80655ca903f5fb568276fe7cfc13d4eb57778d73694907bef35df8db228a';
}

$php = '/www/server/php/74/bin/php';
$moduleDir = '/home/dmdba/dmdbms/drivers/php_pdo/';
$childCommand = escapeshellarg($php)
    . ' -d display_errors=0 -d log_errors=0'
    . ' -d extension=' . escapeshellarg($moduleDir . 'libphp74_dm.so')
    . ' -d extension=' . escapeshellarg($moduleDir . 'php74_pdo_dm.so')
    . ' ' . escapeshellarg($runner) . ' ' . escapeshellarg($mode) . ' C';
$process = proc_open($childCommand, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
    $pipes, null, $environment);
if (!is_resource($process)) {
    throw new RuntimeException('C PHP verifier process unavailable');
}
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
$result = json_decode((string)$stdout, true);
if (!is_array($result)) {
    echo json_encode(['status' => 'redacted_child_error', 'exit' => $exitCode,
        'stderr' => $stderr === '' ? 'empty' : 'nonempty']), PHP_EOL;
    exit($exitCode === 0 ? 2 : $exitCode);
}
echo json_encode(['exit' => $exitCode, 'result' => $result,
    'stderr' => $stderr === '' ? 'empty' : 'nonempty'], JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($exitCode);
