<?php
declare(strict_types=1);

$root = '/tmp/zhct-dm-poc-20260928.fcpiiN/store';
$php = '/www/server/php/73/bin/php';
$lib = '/home/dmdba/dmdbms/drivers/php_pdo/libphp73_dm.so';
$pdo = '/home/dmdba/dmdbms/drivers/php_pdo/php73_pdo_dm.so';
foreach ([$php, $lib, $pdo, $root . '/public/index.php'] as $file) {
    if (!is_file($file)) throw new RuntimeException('Required runtime file missing');
}
foreach (['HOST', 'PORT', 'SCHEMA', 'USER', 'PASSWORD', 'AI_HOST', 'AI_PORT',
    'AI_SCHEMA', 'AI_USER', 'AI_PASSWORD'] as $key) {
    if (!getenv('POC_' . $key)) throw new RuntimeException('Isolated connection setting missing');
}
if (@fsockopen('127.0.0.1', 18080, $errno, $errstr, 1)) {
    throw new RuntimeException('Port 18080 is already occupied');
}
foreach (['APP_ROOT' => $root, 'TARGET_ROOT' => $root, 'DIALECT' => 'dm',
    'EXTERNAL_STUBS' => '1', 'REAL_QUEUE' => '0', 'REDIS_HOST' => '127.0.0.1',
    'REDIS_PORT' => '16379', 'FAIL_ACCOUNT_SETTLEMENT' => '0',
    'FAIL_ACCOUNT_REFUND' => '0', 'FAIL_STORE_ORDER_INSERT' => '0',
    'FAIL_AI_COMMIT' => '0', 'FAIL_QUEUE_PUSH' => '0'] as $key => $value) {
    putenv('POC_' . $key . '=' . $value);
}
$args = [$php, '-c', '/www/server/php/73/etc/php-cli.ini', '-d', 'extension=' . $lib,
    '-d', 'extension=' . $pdo, '-S', '127.0.0.1:18080', '-t', $root . '/public',
    $root . '/public/index.php'];
$command = 'nohup ' . implode(' ', array_map('escapeshellarg', $args))
    . ' >> ' . escapeshellarg('/tmp/zhct-dm-poc-20260928.fcpiiN/store-http-resume-20261001.log')
    . ' 2>&1 < /dev/null & echo $!';
exec($command, $lines, $exit);
if ($exit !== 0 || !ctype_digit(trim((string)($lines[0] ?? '')))) {
    throw new RuntimeException('Store isolated server did not start');
}
echo json_encode(['started_pid' => (int)$lines[0], 'port' => 18080]) . PHP_EOL;
