<?php
declare(strict_types=1);
$lane=$argv[1]??'';$action=$argv[2]??'';if(!in_array($lane,['B','C'],true)||!in_array($action,['final_audit','final_read','export_final','export_green','green','model_test_v1','model_test','upload_probe','recover','preflight','metadata','start','run','stop','export','cleanup'],true))exit(78);$env=getenv();$port=$lane==='B'?18431:18432;
if($lane==='B'){$ini=parse_ini_file('/workspace/zhct/zhctproject/ai_api/.env.local',true,INI_SCANNER_RAW);foreach(['DATABASE'=>'POC_AI_','DATABASE_ZHCT'=>'POC_'] as $s=>$prefix){$v=array_merge(['HOSTPORT'=>'3306','CHARSET'=>'utf8','PREFIX'=>'yoshop_'],$ini[$s]??[]);foreach(['HOSTNAME'=>'HOST','HOSTPORT'=>'PORT','DATABASE'=>'SCHEMA','USERNAME'=>'USER','PASSWORD'=>'PASSWORD','CHARSET'=>'CHARSET','PREFIX'=>'PREFIX'] as $f=>$t){if(!isset($v[$f]))throw new RuntimeException('Local private config incomplete');$env[$prefix.$t]=$v[$f];}}$env['POC_DIALECT']='mysql';$php=['/usr/local/php7.4/bin/php'];$old='/tmp/zhct-http-ai-mysql.j2nxVv';}
else{$cmd=file_get_contents('/proc/53772/cmdline');if(strpos($cmd,'127.0.0.1:18102')===false)throw new RuntimeException('DM parent identity drift');$env=[];foreach(explode("\0",file_get_contents('/proc/53772/environ')) as $entry){$p=explode('=',$entry,2);if(count($p)===2)$env[$p[0]]=$p[1];}if(($env['POC_AI_HOST']??'')!=='127.0.0.1'||($env['POC_AI_PORT']??'')!=='5238'||($env['POC_AI_SCHEMA']??'')!=='AIZHCT_APP')throw new RuntimeException('DM target 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'];$ext=__DIR__.'/private/fileinfo-build/modules/fileinfo.so';if(!is_file($ext))$ext=__DIR__.'/private/evidence/fileinfo.so';$php=array_merge($php,['-d','extension='.$ext]);$old='/tmp/zhct-ai-http-20260929.3XDj3w';}
$env['SIGN_LANE']=$lane;$env['SIGN_BASE']='http://127.0.0.1:'.$port;$env['SIGN_ROOT']=__DIR__.'/source';$env['SIGN_RUNTIME']=__DIR__.'/private';$env['POC_TARGET_ROOT']=$env['SIGN_ROOT'];$env['POC_EXTERNAL_STUBS']='1';$env['POC_REAL_QUEUE']='0';$env['SIGN_CLI']='/tmp/cdx-apifox-cli-2.2.8-cache/package/bin/cli.js';
if($action==='start')$php=array_merge($php,['-d','allow_url_fopen=0','-d','disable_functions=curl_init,curl_setopt,curl_exec,curl_close,curl_multi_init,curl_multi_exec,fsockopen,stream_socket_client']);
if($action==='start'){if($s=@fsockopen('127.0.0.1',$port,$e,$m,1)){fclose($s);throw new RuntimeException('Private port occupied');}foreach(['vendor','config','route'] as $n)if(!file_exists(__DIR__.'/source/'.$n))symlink($old.'/'.$n,__DIR__.'/source/'.$n);foreach(['public','runtime'] as $n)if(!is_dir(__DIR__.'/source/'.$n))mkdir(__DIR__.'/source/'.$n,0700);$args=array_merge($php,['-d','display_errors=0','-d','log_errors=0','-S','127.0.0.1:'.$port,'-t',__DIR__,__DIR__.'/router.php']);$cmd='nohup '.implode(' ',array_map('escapeshellarg',$args)).' </dev/null >/dev/null 2>&1 & echo $!';$p=proc_open($cmd,[1=>['pipe','w'],2=>['pipe','w']],$pipes,null,$env);$pid=trim(stream_get_contents($pipes[1]));$err=stream_get_contents($pipes[2]);fclose($pipes[1]);fclose($pipes[2]);if(proc_close($p)!==0||!ctype_digit($pid)||$err!=='')throw new RuntimeException('Private worker start failed');file_put_contents(__DIR__.'/private/state.json',json_encode(['pid'=>(int)$pid,'port'=>$port]));chmod(__DIR__.'/private/state.json',0600);echo json_encode(['lane'=>$lane,'pid'=>(int)$pid,'port'=>$port]),"\n";exit;}
if($action==='stop'){$s=json_decode(file_get_contents(__DIR__.'/private/state.json'),true);$cmd=str_replace("\0",' ',file_get_contents('/proc/'.$s['pid'].'/cmdline'));if(strpos($cmd,__DIR__.'/router.php')===false||strpos($cmd,':'.$port)===false)throw new RuntimeException('Worker identity mismatch');posix_kill($s['pid'],SIGTERM);usleep(200000);$socket=@fsockopen('127.0.0.1',$port,$e,$m,1);if($socket){fclose($socket);throw new RuntimeException('Port remains open');}echo '{"stopped":true,"port_closed":true}',"\n";exit;}
$env['SIGN_PHASE']=$action==='final_read'?'F':'G';$env['SIGN_RECOVER']=$action==='recover'?'1':'0';if($action==='recover')$action='run';$p=proc_open(array_merge($php,[__DIR__.'/'.$action.'.php']),[0=>STDIN,1=>STDOUT,2=>STDERR],$pipes,null,$env);exit(proc_close($p));
