<?php
declare(strict_types=1);
$lane=$argv[1]??'';$action=$argv[2]??'';
if(!in_array($lane,['B','C'],true)||!in_array($action,['preflight','start','run','retest','stop'],true)){exit(78);}
$root=$lane==='B'?'/tmp/cdx-admin-coupon-B-GfKT5Q/app-root':'/tmp/cdx-admin-coupon-C-FED4to/app-root';$port=$lane==='B'?18361:18362;$runtime=dirname($root).'/worker-runtime';
if(!is_dir($runtime)){mkdir($runtime,0700);}if(hash_file('sha256',$root.'/app/api/model/Coupon.php')!=='17f35c7471ae9ffdd5e824a49a7da6ba4a3ee8f35d1445b8987348202ef131da'){throw new RuntimeException('Locked serializer drift');}
$state=__DIR__.'/ai_'.$lane.'_state.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','CHARSET'=>'CHARSET'] as $from=>$to){if(!isset($ini[$section][$from])){throw new RuntimeException('Local config missing');}$env[$prefix.$to]=$ini[$section][$from];}}
    $env['POC_DIALECT']='mysql';$args=['/opt/homebrew/Cellar/php@7.4/7.4.33_13/bin/php'];
}else{
    $cmd=(string)file_get_contents('/proc/53772/cmdline');if(strpos($cmd,'127.0.0.1:18102')===false){throw new RuntimeException('Approved env source drift');}
    $env=[];foreach(explode("\0",(string)file_get_contents('/proc/53772/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('Nonproduction env gate');}
    $args=['/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['PILOT_LANE']=$lane;$env['PILOT_RUNTIME']=$runtime;$env['COUPON_APP_ROOT']=$root;$env['POC_TARGET_ROOT']=$root;$env['PILOT_TARGET_ROOT']=$root;$env['POC_EXTERNAL_STUBS']='1';$env['POC_REAL_QUEUE']='0';$env['POC_BASE_URL']='http://127.0.0.1:'.$port;
if(in_array($action,['preflight','run','retest'],true)){
    $script=$action==='preflight'?'preflight.php':($action==='retest'?'retest.php':'run.php');$p=proc_open(array_merge($args,['-d','display_errors=0','-d','log_errors=0',__DIR__.'/'.$script]),[0=>STDIN,1=>STDOUT,2=>STDERR],$pipes,null,$env);exit(proc_close($p));
}
if($action==='stop'){
    $data=json_decode((string)file_get_contents($state),true);$cmd=$lane==='C'?(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('Worker stop identity gate');}posix_kill((int)$data['pid'],SIGTERM);file_put_contents($runtime.'/worker-state-final.json',json_encode($data));unlink($state);echo '{"stopped":true}',PHP_EOL;exit;
}
if(is_file($state)){throw new RuntimeException('Prior state exists, inspect before start');}
if($s=@fsockopen('127.0.0.1',$port,$errno,$error,1)){fclose($s);throw new RuntimeException('Owned port busy');}
$args=array_merge($args,['-d','display_errors=0','-d','log_errors=0','-S','127.0.0.1:'.$port,'-t',__DIR__,__DIR__.'/router.php']);
if($lane==='B'){$p=proc_open($args,[0=>['file','/dev/null','r'],1=>['file','/dev/null','a'],2=>['file','/dev/null','a']],$pipes,null,$env);$pid=proc_get_status($p)['pid'];}
else{$command='nohup '.implode(' ',array_map('escapeshellarg',$args)).' </dev/null >/dev/null 2>&1 & echo $!';$p=proc_open($command,[1=>['pipe','w'],2=>['pipe','w']],$pipes,null,$env);$out=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($out)||$err!==''){throw new RuntimeException('Private start failed');}$pid=(int)$out;}
$data=['lane'=>$lane,'root'=>$root,'runtime'=>$runtime,'port'=>$port,'pid'=>$pid];file_put_contents($state,json_encode($data));chmod($state,0600);echo json_encode($data),PHP_EOL;flush();if($lane==='B'){exit(proc_close($p));}
