#!/usr/bin/env python3
import shlex
import subprocess
import sys
from pathlib import Path
root=Path(__file__).parent
lane=sys.argv[1]
assert lane in ('B','C')
runtime='/tmp/cdx-store-category9-B.cVux2z' if lane=='B' else '/tmp/cdx-store-category9-C.Hr1w83'
pid=10001 if lane=='B' else 112175
php='/usr/local/php7.3/bin/php' if lane=='B' else '/www/server/php/73/bin/php'
child=[php]
if lane=='C':child+=['-c','/www/server/php/73/etc/php-cli.ini','-d','extension=/home/dmdba/dmdbms/drivers/php_pdo/libphp73_dm.so','-d','extension=/home/dmdba/dmdbms/drivers/php_pdo/php73_pdo_dm.so']
child+=[runtime+'/schema-api-run.php']
child_command=' '.join(shlex.quote(a) for a in child)
wrapper='$env=[];foreach(explode(chr(0),file_get_contents("/proc/'+str(pid)+'/environ")) as $s){$v=explode("=",$s,2);if(count($v)===2)$env[$v[0]]=$v[1];}if(($env["POC_EXTERNAL_STUBS"]??"")!=="1"||($env["POC_REAL_QUEUE"]??"0")!=="0")exit(78);$env["PM_LANE"]="'+lane+'";$env["PM_ROOT"]="'+('/tmp/zhct-http-store-mysql.dQTTBP' if lane=='B' else '/tmp/zhct-dm-poc-20260928.fcpiiN/store')+'";$p=proc_open('+repr(child_command)+',[0=>STDIN,1=>STDOUT,2=>STDERR],$pipes,null,$env);exit(proc_close($p));'
command=['docker','exec','-i','zhctapp_v2_0',php,'-r',wrapper] if lane=='B' else ['ssh','-S','/private/tmp/cdx-train-root-20261010.sock','-o','BatchMode=yes','root@121.43.241.161',php+' -r '+shlex.quote(wrapper)]
evidence=root/'api-private-evidence'/lane
assert not (evidence/'run.stdout').exists(),'No lane replay'
with (evidence/'run.stdout').open('xb')as output,(evidence/'run.stderr').open('xb')as error:
    (evidence/'run.stdout').chmod(0o600);(evidence/'run.stderr').chmod(0o600)
    result=subprocess.run(command,stdout=output,stderr=error,check=False)
print(lane,'exit',result.returncode)
print((evidence/'run.stdout').read_text())
raise SystemExit(result.returncode)
