<?php
declare(strict_types=1);
// Secrets stay in child-process environment. Output contains no connection values.
$lane = $argv[1] ?? ''; $action = $argv[2] ?? '';
if (!in_array($lane, ['B','C'], true) || !in_array($action, ['start','run','stop'], true)) exit(78);
$state = __DIR__ . '/ai_' . $lane . '_state.json';
$port = $lane === 'B' ? 18251 : 18252;
$root = $lane === 'B' ? '/private/tmp/zhct-http-ai-macos.x2CCZX'
    : '/tmp/zhct-ai-http-20260929.3XDj3w';
$env = getenv();
if ($lane === 'B') {
    $file = '/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local';
    $ini = parse_ini_file($file, true, INI_SCANNER_RAW);
    foreach (['DATABASE' => 'POC_AI_', 'DATABASE_ZHCT' => 'POC_'] as $section => $prefix) {
        foreach (['HOSTNAME'=>'HOST','HOSTPORT'=>'PORT','DATABASE'=>'SCHEMA','USERNAME'=>'USER','PASSWORD'=>'PASSWORD'] as $from=>$to) {
            if (!isset($ini[$section][$from])) throw new RuntimeException('Local config incomplete');
            $env[$prefix . $to] = $ini[$section][$from];
        }
    }
    $env['POC_DIALECT'] = 'mysql';
    $php = '/opt/homebrew/Cellar/php@7.4/7.4.33_13/bin/php'; $phpArgs = [$php];
} else {
    $pid = 53772;
    $cmd = (string)file_get_contents('/proc/' . $pid . '/cmdline');
    if (strpos($cmd, '127.0.0.1:18102') === false
        || strpos($cmd, '/tmp/zhct-ai-http-20260929.3XDj3w') === false) throw new RuntimeException('C worker drift');
    $env = [];
    foreach (explode("\0", (string)file_get_contents('/proc/' . $pid . '/environ')) as $entry) {
        $pair = explode('=', $entry, 2); if (count($pair) === 2) $env[$pair[0]] = $pair[1];
    }
    if (($env['POC_AI_HOST'] ?? '') !== '127.0.0.1' || ($env['POC_AI_PORT'] ?? '') !== '5238'
        || ($env['POC_AI_SCHEMA'] ?? '') !== 'AIZHCT_APP') throw new RuntimeException('C identity drift');
    $php = '/www/server/php/74/bin/php';
    $phpArgs = [$php, '-c', '/www/server/php/74/etc/php-cli.ini',
        '-d', 'extension=/home/dmdba/dmdbms/drivers/php_pdo/libphp74_dm.so',
        '-d', 'extension=/home/dmdba/dmdbms/drivers/php_pdo/php74_pdo_dm.so'];
}
$env['POC_EXTERNAL_STUBS'] = '1'; $env['POC_REAL_QUEUE'] = '0';
$env['POC_TARGET_ROOT'] = $root; $env['PILOT_TARGET_ROOT'] = $root;
$env['POC_BASE_URL'] = 'http://127.0.0.1:' . $port; $env['PILOT_LANE'] = $lane;
if ($action === 'start') {
    if (is_file($state)) {
        $old=json_decode((string)file_get_contents($state),true);
        if (posix_kill((int)$old['pid'],0)) throw new RuntimeException('State already exists');
        unlink($state);
    }
    if ($socket = @fsockopen('127.0.0.1', $port, $errno, $error, 1)) {
        fclose($socket); throw new RuntimeException('Pilot port occupied');
    }
    $runtime = tempnam(sys_get_temp_dir(), 'cdx-ai-coverage-' . $lane . '-');
    unlink($runtime); mkdir($runtime, 0700); $env['PILOT_RUNTIME'] = $runtime;
    $args = array_merge($phpArgs, ['-d','display_errors=0','-d','log_errors=0',
        '-S','127.0.0.1:' . $port, '-t',__DIR__,__DIR__ . '/ai_router.php']);
    if ($lane === 'B') {
        $proc=proc_open($args,[0=>['file','/dev/null','r'],1=>['file','/dev/null','a'],2=>['file','/dev/null','a']],$pipes,null,$env);
        $status=proc_get_status($proc);$data=['lane'=>$lane,'pid'=>$status['pid'],'port'=>$port,'runtime'=>$runtime];
        file_put_contents($state,json_encode($data));chmod($state,0600);echo json_encode($data),"\n";flush();
        exit(proc_close($proc));
    }
    $command = 'nohup ' . implode(' ', array_map('escapeshellarg', $args)) . ' </dev/null >/dev/null 2>&1 & echo $!';
    $proc = proc_open($command, [1=>['pipe','w'],2=>['pipe','w']], $pipes, null, $env);
    $out = stream_get_contents($pipes[1]); $err=stream_get_contents($pipes[2]);
    fclose($pipes[1]); fclose($pipes[2]); $exit=proc_close($proc);
    if ($exit !== 0 || !ctype_digit(trim($out)) || $err !== '') throw new RuntimeException('Start failed');
    $data=['lane'=>$lane,'pid'=>(int)trim($out),'port'=>$port,'runtime'=>$runtime];
    file_put_contents($state,json_encode($data)); chmod($state,0600); echo json_encode($data),"\n";
} else {
    $data=json_decode((string)file_get_contents($state),true);
    $env['PILOT_RUNTIME']=$data['runtime'];
    if ($action === 'stop') {
        // Exact worker-only PID, verified command identity before signalling.
        $cmd = $lane === 'C' ? str_replace("\0", ' ', (string)file_get_contents('/proc/' . $data['pid'] . '/cmdline'))
            : (string)shell_exec('ps -p ' . (int)$data['pid'] . ' -o command=');
        if (strpos($cmd, __DIR__ . '/ai_router.php') === false || strpos($cmd, '127.0.0.1:' . $port) === false) {
            throw new RuntimeException('Stop identity mismatch');
        }
        posix_kill((int)$data['pid'], SIGTERM); echo '{"stopped":true}',"\n";
    } else {
        $args=array_merge($phpArgs,[__DIR__.'/ai_run.php']);
        $proc=proc_open($args,[0=>STDIN,1=>STDOUT,2=>STDERR],$pipes,null,$env);
        exit(proc_close($proc));
    }
}
