<?php
declare(strict_types=1);

$mode = (string)($argv[1] ?? '');
if (count($argv) !== 2 || !in_array($mode, ['--preflight', '--execute', '--audit'], true)
    || ($mode === '--execute'
        && (string)getenv('CDX_PAL3_C_RELEASE') !== 'ROOT_NATURAL_READ3_V1')) {
    echo json_encode(['status' => 'default_deny', 'http_sent' => false, 'dml' => false]), PHP_EOL;
    exit(78);
}
$pid = 112175;
$command = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
if (strpos($command, '/tmp/zhct-dm-poc-20260928.fcpiiN/store/public') === false
    || strpos($command, '127.0.0.1:18080') === false) {
    throw new RuntimeException('C worker drift');
}
$env = [];
foreach (explode("\0", (string)@file_get_contents('/proc/' . $pid . '/environ')) as $item) {
    $at = strpos($item, '=');
    if ($at !== false) $env[substr($item, 0, $at)] = substr($item, $at + 1);
}
$servicePath = (string)($env['DM_SVC_PATH'] ?? '');
if (($env['POC_PORT'] ?? '') !== '5237' || ($env['POC_SCHEMA'] ?? '') !== 'ZHCT_APP'
    || substr(hash('sha256', $servicePath), 0, 12) !== '5a92d26aec07'
    || !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 drift');
}
$runner = __DIR__ . '/runner.php';
$expected = '3af688e02b6c52c71c1166247abf98c729b95ab77a3918387d63633f7d304d22';
if (is_link(__DIR__) || is_link($runner) || !is_file($runner)
    || (fileperms(__DIR__) & 0777) !== 0700
    || (fileperms($runner) & 0777) !== 0600
    || hash_file('sha256', $runner) !== $expected) {
    throw new RuntimeException('C runner drift');
}
$env['CDX_PAL3_LANE'] = 'C';
if ($mode === '--execute') {
    $env['CDX_PAL3_APPROVE'] = 'ROOT_NATURAL_READ3_V1';
    $env['CDX_PAL3_SHA'] = $expected;
} elseif ($mode === '--audit') {
    $env['CDX_PAL3_JOURNAL'] = (string)getenv('CDX_PAL3_C_JOURNAL');
}
$cmd = 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($cmd, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, $env);
if (!is_resource($process)) throw new RuntimeException('C child unavailable');
$stdout = stream_get_contents($pipes[1]); $stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]); fclose($pipes[2]); $exit = proc_close($process);
$result = json_decode((string)$stdout, true);
if (!is_array($result)) {
    echo json_encode(['status' => 'redacted_child_error', 'exit' => $exit,
        'stderr' => $stderr === '' ? 'empty' : 'nonempty']), PHP_EOL;
    exit($exit === 0 ? 2 : $exit);
}
echo json_encode(['exit' => $exit, 'result' => $result,
    'stderr' => $stderr === '' ? 'empty' : 'nonempty'], JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($exit);
