<?php
declare(strict_types=1);
$lane=$argv[1]??'';if(!in_array($lane,['B','C'],true))exit(78);
$env=[];$keys=['PATH','LANG','TZ','LD_LIBRARY_PATH','DM_HOME','NLS_LANG','DM_CHARSET','DM_SVC_PATH','LC_ALL','LC_CTYPE'];
if($lane==='B'){
 foreach($keys as $k)if(getenv($k)!==false)$env[$k]=getenv($k);
 $ini=parse_ini_file('/workspace/zhct/zhctproject/ai_api/.env.local',true,INI_SCANNER_RAW);
 foreach(['DATABASE'=>'AI','DATABASE_ZHCT'=>'ZHCT'] as $section=>$db){
  $v=array_merge(['HOSTPORT'=>'3306','CHARSET'=>'utf8','PREFIX'=>$db==='AI'?'yoshop_':'ydy_'],$ini[$section]??[]);
  foreach(['HOSTNAME'=>'HOST','HOSTPORT'=>'PORT','DATABASE'=>'SCHEMA','USERNAME'=>'USER','PASSWORD'=>'PASSWORD','CHARSET'=>'CHARSET','PREFIX'=>'PREFIX'] as $f=>$t){if(!array_key_exists($f,$v))throw new RuntimeException('Missing local config key');$env['POC_'.$db.'_'.$t]=$v[$f];}
 }
 $env['POC_DIALECT']='mysql';$env['ROPE_SOURCE']='/workspace/zhct/zhctproject/ai_api';$php=['/usr/local/php7.4/bin/php'];
}else{
 if(strpos(file_get_contents('/proc/53772/cmdline'),'127.0.0.1:18102')===false)throw new RuntimeException('Known parent identity drift');
 foreach(['AI','STORE','ZHCT'] as $db)foreach(['HOST','PORT','SCHEMA','USER','PASSWORD','CHARSET','PREFIX'] as $k)$keys[]='POC_'.$db.'_'.$k;$keys[]='POC_DIALECT';
 foreach(explode("\0",file_get_contents('/proc/53772/environ')) as $e){$p=explode('=',$e,2);if(count($p)===2&&in_array($p[0],$keys,true))$env[$p[0]]=$p[1];}unset($e,$p);
 if(($env['POC_AI_HOST']??'')!=='127.0.0.1'||($env['POC_AI_PORT']??'')!=='5238'||($env['POC_AI_SCHEMA']??'')!=='AIZHCT_APP')throw new RuntimeException('Target drift');
 $parentCmd=file_get_contents('/proc/112175/cmdline');if(strpos($parentCmd,'/tmp/zhct-dm-poc-20260928.fcpiiN/store')===false)throw new RuntimeException('Original Store parent identity drift');
 $secondary=[];foreach(explode("\0",file_get_contents('/proc/112175/environ')) as $entry){$pair=explode('=',$entry,2);if(count($pair)===2&&in_array($pair[0],['POC_HOST','POC_PORT','POC_SCHEMA','POC_USER','POC_PASSWORD'],true))$secondary[substr($pair[0],4)]=$pair[1];}unset($entry,$pair);
 if(($secondary['HOST']??'')!=='127.0.0.1'||($secondary['PORT']??'')!=='5237'||($secondary['SCHEMA']??'')!=='ZHCT_APP')throw new RuntimeException('Original approved secondary endpoint drift');
 foreach($secondary as $key=>$value)$env['POC_ZHCT_'.$key]=$value;unset($secondary,$key,$value);$env['POC_ZHCT_PREFIX']='ydy_';$env['POC_ZHCT_CHARSET']='utf8';
 $env['POC_AI_PREFIX']='yoshop_';$env['POC_AI_CHARSET']='utf8';
 $env['ROPE_SOURCE']='/tmp/zhct-ai-http-20260929.3XDj3w';$env['ROPE_VALIDATOR']=__DIR__.'/private/RopeSkippingValidate.php';
 $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'];
}
$env['ROPE_LANE']=$lane;$stage=$argv[2]??'preflight';if(!in_array($stage,['preflight','preflight-auth','fixture','setup','run','start','stop','cleanup','final-read'],true))exit(78);
if(in_array($stage,['start','stop'],true)){
 $port=$lane==='B'?18901:18902;$state=__DIR__.'/private/worker-state.json';
 if($stage==='start'){
  if($socket=@fsockopen('127.0.0.1',$port,$e,$m,1)){fclose($socket);throw new RuntimeException('Own worker collision');}if(file_exists($state))throw new RuntimeException('Own worker state exists');
  $args=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','-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('Worker launch');file_put_contents($state,json_encode(['pid'=>(int)$pid,'port'=>$port]));chmod($state,0600);echo json_encode(['lane'=>$lane,'own_worker_pid'=>(int)$pid,'port'=>$port,'collision_zero'=>true]),"\n";exit;
 }
 $s=json_decode(file_get_contents($state),true);$cmd=file_get_contents('/proc/'.$s['pid'].'/cmdline');if(strpos($cmd,__DIR__.'/router.php')===false||strpos($cmd,':'.$port)===false)throw new RuntimeException('Worker identity drift');posix_kill($s['pid'],SIGTERM);usleep(200000);if($socket=@fsockopen('127.0.0.1',$port,$e,$m,1)){fclose($socket);throw new RuntimeException('Worker remains');}echo json_encode(['lane'=>$lane,'worker_stopped'=>true,'port_closed'=>true]),"\n";exit;
}
$p=proc_open(array_merge($php,[__DIR__.'/'.$stage.'.php']),[0=>STDIN,1=>STDOUT,2=>STDERR],$pipes,null,$env);exit(proc_close($p));
