<?php

declare(strict_types=1);

$lane = $argv[1] ?? '';
if (!in_array($lane, ['B', 'C'], true)) exit(2);
$parentPid = $lane === 'B' ? 10001 : 112175;
$parentRoot = $lane === 'B'
    ? '/tmp/zhct-http-store-mysql.dQTTBP'
    : '/tmp/zhct-dm-poc-20260928.fcpiiN/store';
$root = '/tmp/cdx-prepay-code-scan-20261012-' . $lane . '-store';
$port = $lane === 'B' ? 19131 : 19132;
if (strpos((string)file_get_contents('/proc/' . $parentPid . '/cmdline'), $parentRoot . '/public') === false
    || !is_file($root . '/application/api/controller/PrepayOrder.php')
    || !is_file($root . '/extend/vendor/autoload.php')
    || !is_file($root . '/public/private_store_router.php')
    || is_file($root . '/private-http.pid')) {
    throw new RuntimeException('Store parent/source/extend/own router preflight failed');
}
$allow = ['PATH', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ', 'NLS_LANG', 'DM_CHARSET',
    'DM_SVC_PATH', 'DM_HOME', 'LD_LIBRARY_PATH', 'POC_HOST', 'POC_PORT',
    'POC_SCHEMA', 'POC_USER', 'POC_PASSWORD', 'POC_AI_HOST', 'POC_AI_PORT',
    'POC_AI_SCHEMA', 'POC_AI_USER', 'POC_AI_PASSWORD', 'POC_DIALECT',
    'POC_PREFIX', 'POC_CHARSET', 'POC_REDIS_HOST', 'POC_REDIS_PORT',
    'POC_EXTERNAL_STUBS'];
$env = [];
foreach (explode("\0", (string)file_get_contents('/proc/' . $parentPid . '/environ')) as $pair) {
    $parts = explode('=', $pair, 2);
    if (count($parts) === 2 && in_array($parts[0], $allow, true)) $env[$parts[0]] = $parts[1];
}
if ($lane === 'B') {
    $cfg = require $root . '/application/database.php';
    $local = require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
    foreach (['hostname', 'hostport', 'database', 'username', 'password'] as $field) {
        $default = $field === 'hostport' ? '3306' : '';
        if ((string)($cfg[$field] ?? $default) !== (string)($local[$field] ?? $default)
            || (string)($cfg['ai_zhct'][$field] ?? $default) !== (string)($local['ai_zhct'][$field] ?? $default)) {
            throw new RuntimeException('B config differs from local development DB');
        }
    }
    $map = ['hostname' => 'HOST', 'hostport' => 'PORT', 'database' => 'SCHEMA',
        'username' => 'USER', 'password' => 'PASSWORD'];
    foreach ($map as $key => $suffix) {
        $env['POC_' . $suffix] = (string)($cfg[$key] ?? ($key === 'hostport' ? 3306 : ''));
        $env['POC_AI_' . $suffix] = (string)($cfg['ai_zhct'][$key] ?? ($key === 'hostport' ? 3306 : ''));
    }
    $env['POC_DIALECT'] = 'mysql';
}
foreach (['POC_HOST', 'POC_PORT', 'POC_SCHEMA', 'POC_USER', 'POC_PASSWORD',
    'POC_AI_HOST', 'POC_AI_PORT', 'POC_AI_SCHEMA', 'POC_AI_USER', 'POC_AI_PASSWORD'] as $key) {
    if (!isset($env[$key]) || $env[$key] === '') throw new RuntimeException('Private DB env incomplete');
}
if (($env['POC_EXTERNAL_STUBS'] ?? '') !== '1'
    || ($env['POC_DIALECT'] ?? '') !== ($lane === 'B' ? 'mysql' : 'dm')) {
    throw new RuntimeException('External/dialect boundary invalid');
}
$env['POC_REAL_QUEUE'] = '0';
$env['POC_APP_ROOT'] = $root;
$env['POC_BASE_URL'] = 'http://127.0.0.1:' . $port;
$args = [$lane === 'B' ? '/usr/local/php7.3/bin/php' : '/www/server/php/73/bin/php'];
if ($lane === 'C') array_push($args, '-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');
array_push($args, '-d', 'display_errors=0', '-d', 'log_errors=1',
    '-S', '127.0.0.1:' . $port, '-t', $root . '/public',
    $root . '/public/private_store_router.php');
$cmd = 'nohup ' . implode(' ', array_map('escapeshellarg', $args))
    . ' </dev/null >' . escapeshellarg($root . '/private-http.log') . ' 2>&1 & echo $!';
$process = proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes, null, $env);
if (!is_resource($process)) throw new RuntimeException('Could not launch private Store');
$pid = (int)trim(stream_get_contents($pipes[1]));
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
if ($pid <= 1) throw new RuntimeException('Private Store PID unavailable');
file_put_contents($root . '/private-http.pid', (string)$pid, LOCK_EX);
chmod($root . '/private-http.pid', 0600);
echo json_encode(['lane' => $lane, 'port' => $port, 'private_pid' => $pid,
    'source' => 'current Store application overlay with extend dependency']) . PHP_EOL;
