<?php
declare(strict_types=1);
$lane = $argv[1] ?? '';
if (!in_array($lane, ['B', 'C'], true)) exit(78);
$pid = $lane === 'B' ? 10001 : 112175;
$root = $lane === 'B' ? '/tmp/zhct-http-store-mysql.dQTTBP' : '/tmp/zhct-dm-poc-20260928.fcpiiN/store';
if (strpos((string)file_get_contents('/proc/' . $pid . '/cmdline'), $root . '/public') === false) {
    throw new RuntimeException('Worker drift');
}
$environment = [];
foreach (explode("\0", (string)file_get_contents('/proc/' . $pid . '/environ')) as $entry) {
    $pair = explode('=', $entry, 2);
    if (count($pair) === 2) $environment[$pair[0]] = $pair[1];
}
$environment['CDX_MEAL_WIDE_RUN'] = 'ONE_NONPAYMENT_ORDER_V1';
$environment['CDX_DMR9_LANE'] = $lane;
$environment['CDX_DMR9_RUN'] = 'ONE_PAGE_READ_V1';
$environment['POC_BASE_URL'] = $lane === 'B' ? 'http://127.0.0.1:18082' : 'http://127.0.0.1:18083';
$environment['POC_DIALECT'] = $lane === 'B' ? 'mysql' : 'dm';
if ($lane === 'B') {
    $local = require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
    foreach (['hostname' => 'HOST', 'hostport' => 'PORT', 'database' => 'SCHEMA',
        'username' => 'USER', 'password' => 'PASSWORD'] as $key => $suffix) {
        $environment['POC_' . $suffix] = (string)($local[$key] ?? ($key === 'hostport' ? 3306 : ''));
    }
}
$php = $lane === 'B' ? '/usr/local/php7.3/bin/php' : '/www/server/php/73/bin/php';
$baseArgs = [$php, '-d', 'display_errors=0', '-d', 'log_errors=0'];
if ($lane === 'C') {
    array_push($baseArgs, '-c', '/www/server/php/73/etc/php-cli.ini',
        '-d', 'extension=/home/dmdba/dmdbms/drivers/php_pdo/libphp73_dm.so',
        '-d', 'extension=/home/dmdba/dmdbms/drivers/php_pdo/php73_pdo_dm.so');
}
$jobs = [['meal_wide_run.php', $lane, '--run'], ['meal_wide_run.php', $lane, '--audit'],
    ['recipes_run.php', '--run'], ['device_recipes_run.php'], ['device_recipes_run.php', '--audit']];
if (($argv[2] ?? '') === '--audit-only') $jobs = [['device_recipes_run.php', '--audit']];
$all = true;
foreach ($jobs as $job) {
    $args = array_merge($baseArgs, [__DIR__ . '/' . array_shift($job)], $job);
    $process = proc_open(implode(' ', array_map('escapeshellarg', $args)),
        [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, $environment);
    $out = stream_get_contents($pipes[1]); $err = stream_get_contents($pipes[2]);
    fclose($pipes[1]); fclose($pipes[2]); $exit = proc_close($process);
    $result = json_decode(trim($out), true);
    $all = $all && $exit === 0 && is_array($result);
    $evidence = ['lane' => $lane, 'job' => basename($args[count($baseArgs)]),
        'exit' => $exit, 'result' => $result, 'stderr_empty' => $err === ''];
    $line = json_encode($evidence) . "\n";
    file_put_contents(__DIR__ . '/results-' . $lane . '.jsonl', $line, FILE_APPEND | LOCK_EX);
    chmod(__DIR__ . '/results-' . $lane . '.jsonl', 0600);
    echo $line;
    if ($exit !== 0) break; // Never continue after ambiguous write cleanup.
}
exit($all ? 0 : 2);
