<?php
declare(strict_types=1);
$lane=$argv[1]??'';$action=$argv[2]??'';
if(!in_array($lane,['B','C'],true)||!in_array($action,['start','run','audit','stop'],true))exit(78);
$port=$lane==='B'?18281:18282;$state=__DIR__.'/state-'.$lane.'.json';$env=getenv();
if($lane==='B'){
    $ini=parse_ini_file('/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local',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('Incomplete local config');$env[$prefix.$to]=$ini[$section][$from];}
    $env['POC_DIALECT']='mysql';$php=['/opt/homebrew/Cellar/php@7.4/7.4.33_13/bin/php'];
    $old='/private/tmp/zhct-http-ai-macos.x2CCZX';
}else{
    $cmd=(string)file_get_contents('/proc/53772/cmdline');
    if(strpos($cmd,'127.0.0.1:18102')===false)throw new RuntimeException('C parent worker identity drift');
    $env=[];foreach(explode("\0",(string)file_get_contents('/proc/53772/environ')) as $entry){
        $parts=explode('=',$entry,2);if(count($parts)===2)$env[$parts[0]]=$parts[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 database drift');
    $php=['/www/server/php/74/bin/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'];
    $old='/tmp/zhct-ai-http-20260929.3XDj3w';
}
$env['POC_EXTERNAL_STUBS']='1';$env['POC_REAL_QUEUE']='0';$env['CATEGORY_LANE']=$lane;$env['CATEGORY_BASE']='http://127.0.0.1:'.$port;
$env['CATEGORY_ROOT']=__DIR__.'/source';
$env['POC_TARGET_ROOT']=$env['CATEGORY_ROOT'];
if($action==='start'){
    if($socket=@fsockopen('127.0.0.1',$port,$errno,$error,1)){fclose($socket);throw new RuntimeException('Private port occupied');}
    foreach(['vendor','config','route'] as $name)if(!file_exists(__DIR__.'/source/'.$name))symlink($old.'/'.$name,__DIR__.'/source/'.$name);
    if(!is_dir(__DIR__.'/source/public'))mkdir(__DIR__.'/source/public',0700);
    if(!is_file(__DIR__.'/source/external_stubs.php'))copy($old.'/external_stubs.php',__DIR__.'/source/external_stubs.php');
    if(!is_dir(__DIR__.'/source/runtime'))mkdir(__DIR__.'/source/runtime',0700);
    $runtime=tempnam(sys_get_temp_dir(),'cdx-ac-'.$lane.'-');unlink($runtime);mkdir($runtime,0700);
    $env['CATEGORY_RUNTIME']=$runtime;
    $args=array_merge($php,['-d','display_errors=0','-d','log_errors=0','-S','127.0.0.1:'.$port,'-t',__DIR__,__DIR__.'/router.php']);
    if($lane==='B'){
        $process=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($process);$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($process));
    }
    $command='nohup '.implode(' ',array_map('escapeshellarg',$args)).' </dev/null >/dev/null 2>&1 & echo $!';
    $process=proc_open($command,[1=>['pipe','w'],2=>['pipe','w']],$pipes,null,$env);
    $out=stream_get_contents($pipes[1]);$error=stream_get_contents($pipes[2]);fclose($pipes[1]);fclose($pipes[2]);$exit=proc_close($process);
    if($exit!==0||!ctype_digit(trim($out))||$error!=='')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['CATEGORY_RUNTIME']=$data['runtime'];
    if($action==='stop'){
        $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__.'/router.php')===false||strpos($cmd,'127.0.0.1:'.$port)===false)throw new RuntimeException('Stop identity drift');
        posix_kill((int)$data['pid'],SIGTERM);echo '{"stopped":true}',"\n";
    }else{
        $process=proc_open(array_merge($php,[__DIR__.'/run.php',$action]),[0=>STDIN,1=>STDOUT,2=>STDERR],$pipes,null,$env);exit(proc_close($process));
    }
}
