<?php

declare(strict_types=1);

// Launch the bounded C test with the existing isolated HTTP worker's entire environment.
$mode = (string)($argv[1] ?? '');
if (!in_array($mode, ['--preflight', '--execute'], true)) {
    fwrite(STDERR, "DENIED: mode\n");
    exit(78);
}
$runner = '/tmp/cdx_em_natural_read_20261004.php';
$expectedRunnerSha = 'b0480e14de770466aaa0b6c9eeb5842d47e3fdefeb155487c63e8e9ef902ffa2';
if (!is_file($runner) || hash_file('sha256', $runner) !== $expectedRunnerSha) {
    fwrite(STDERR, "DENIED: runner SHA drift\n");
    exit(78);
}
if ($mode === '--execute'
    && ((string)getenv('CDX_C_EM_NATURAL_APPROVE') !== 'ROOT_APPROVED_C_NATURAL_READ_V1'
        || (string)getenv('CDX_C_EM_NATURAL_WRAPPER_SHA') !== hash_file('sha256', __FILE__))) {
    fwrite(STDERR, "DENIED: wrapper approval/SHA\n");
    exit(78);
}
$pid = 112175;
$cmdline = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
if (strpos($cmdline, '127.0.0.1:18080') === false
    || strpos($cmdline, '/tmp/zhct-dm-poc-20260928.fcpiiN/store/public') === false) {
    throw new RuntimeException('C isolated worker drift');
}
$worker = [];
foreach (explode("\0", (string)@file_get_contents('/proc/' . $pid . '/environ')) as $entry) {
    $separator = strpos($entry, '=');
    if ($separator !== false) $worker[substr($entry, 0, $separator)] = substr($entry, $separator + 1);
}
$svcPath = (string)($worker['DM_SVC_PATH'] ?? '');
if (substr(hash('sha256', $svcPath), 0, 12) !== '5a92d26aec07'
    || !is_file($svcPath . '/dm_svc.conf')
    || strpos((string)file_get_contents($svcPath . '/dm_svc.conf'), 'CHAR_CODE=(PG_UTF8)') === false
    || (string)($worker['POC_HOST'] ?? '') !== '127.0.0.1'
    || (string)($worker['POC_PORT'] ?? '') !== '5237'
    || (string)($worker['POC_SCHEMA'] ?? '') !== 'ZHCT_APP'
    || (string)($worker['POC_USER'] ?? '') !== 'ZHCT_APP'
    || (string)($worker['POC_EXTERNAL_STUBS'] ?? '') !== '1'
    || (string)($worker['POC_PASSWORD'] ?? '') === '') {
    throw new RuntimeException('C worker client/database boundary drift');
}
$worker['CDX_EM_NATURAL_LANE'] = 'C';
if ($mode === '--execute') {
    $worker['CDX_EM_NATURAL_APPROVE'] = 'ROOT_APPROVED_NATURAL_READ_V1';
    $worker['CDX_EM_NATURAL_SHA'] = $expectedRunnerSha;
    $worker['CDX_EM_NATURAL_DB_SHA'] = 'bc98485aed26beab348770a82ae38dbf922b04ab88a210cd7282c4caf0156194';
}
$command = escapeshellarg('/www/server/php/73/bin/php')
    . ' -d display_errors=0 -d log_errors=0'
    . ' -d extension=/home/dmdba/dmdbms/drivers/php_pdo/php73_pdo_dm.so '
    . escapeshellarg($runner) . ' ' . escapeshellarg($mode);
$process = proc_open($command, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, $worker);
if (!is_resource($process)) throw new RuntimeException('C test child unavailable');
$stdout = (string)stream_get_contents($pipes[1]);
$stderr = (string)stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$status = proc_close($process);
$lines = array_values(array_filter(explode("\n", trim($stdout)), 'strlen'));
$result = json_decode((string)end($lines), true);
if (!is_array($result)) {
    echo json_encode(['status' => 'child_error', 'exit' => $status,
        'stderr' => $stderr === '' ? 'empty' : 'redacted_nonempty']), PHP_EOL;
    exit(2);
}
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($status);
