<?php
declare(strict_types=1);

// Run only the fixed mobile-page getRecipes probe under the approved C worker.
$mode = (string)($argv[1] ?? '');
if (!in_array($mode, ['--preflight', '--run', '--audit'], true)
    || ($mode === '--run' && getenv('CDX_DMR9_RUN') !== 'ONE_PAGE_READ_V1')) {
    fwrite(STDERR, "DENIED mode/run gate\n"); exit(78);
}
$pid = 112175;
$commandLine = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
if (strpos($commandLine, '127.0.0.1:18080') === false
    || strpos($commandLine, '/tmp/zhct-dm-poc-20260928.fcpiiN/store/public') === false) {
    throw new RuntimeException('C isolated Store worker drift');
}
$environment = [];
foreach (explode("\0", (string)@file_get_contents('/proc/' . $pid . '/environ')) as $entry) {
    $offset = strpos($entry, '=');
    if ($offset !== false) $environment[substr($entry, 0, $offset)] = substr($entry, $offset + 1);
}
if (($environment['POC_DIALECT'] ?? '') !== 'dm'
    || ($environment['POC_HOST'] ?? '') !== '127.0.0.1'
    || ($environment['POC_PORT'] ?? '') !== '5237'
    || ($environment['POC_SCHEMA'] ?? '') !== 'ZHCT_APP') {
    throw new RuntimeException('C Store database identity drift');
}
$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 UTF-8 client configuration drift');
}
$runner = __DIR__ . '/verify_recipes_page_positive.php';
if (is_link(__DIR__) || is_link($runner) || !is_file($runner)
    || hash_file('sha256', $runner)
        !== '5b158781b75045fd6ee04edf97e2c5b5c972be8075212773b7cb6e72faed7c69') {
    throw new RuntimeException('C positive probe source drift');
}
$environment['CDX_DMR9_LANE'] = 'C';
if ($mode === '--run') $environment['CDX_DMR9_RUN'] = 'ONE_PAGE_READ_V1';
if ($mode === '--audit') {
    $environment['CDX_DMR9_MARKER'] = (string)getenv('CDX_DMR9_MARKER');
    $environment['CDX_DMR9_SOURCE_SHA'] = (string)getenv('CDX_DMR9_SOURCE_SHA');
}
$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, $environment);
if (!is_resource($process)) throw new RuntimeException('C PHP unavailable');
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]); fclose($pipes[2]);
$exit = proc_close($process);
echo json_encode(['exit' => $exit, 'result' => json_decode((string)$stdout, true),
    'stderr' => $stderr === '' ? 'empty' : 'nonempty'], JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($exit);
