<?php
require __DIR__.'/apps.php';require __DIR__.'/observe.php';
$mode=$argv[1]??'';
if($mode==='workers-ready'){
 $out=[];foreach(['launch-store','launch-ai']as $k){$lease=pp_saved('worker-'.$k.'.json');$cmd=(string)file_get_contents('/proc/'.$lease['pid'].'/cmdline');pp_need(strpos($cmd,__DIR__.'/router.php')!==false&&strpos($cmd,'127.0.0.1:'.$lease['port'])!==false,'Exact recorded own worker command');$s=@fsockopen('127.0.0.1',$lease['port'],$a,$b,.5);pp_need(is_resource($s),'Own worker actual socket bound, no HTTP warmup');fclose($s);$out[$k]=$lease;}pp_save('workers.json',$out);echo pp_json(['status'=>'OWN_TWO_WORKERS_READY_NO_HTTP','side'=>getenv('PP_SIDE')])."\n";exit;
}
if($mode==='cleanup'){
 $removed=[];$workers=[];foreach(['launch-store','launch-ai']as $k){$f=pp_private().'/worker-'.$k.'.json';if(!is_file($f))continue;$lease=pp_saved('worker-'.$k.'.json');$proc='/proc/'.$lease['pid'].'/cmdline';if(is_file($proc)){$cmd=(string)file_get_contents($proc);pp_need(strpos($cmd,__DIR__.'/router.php')!==false&&strpos($cmd,'127.0.0.1:'.$lease['port'])!==false,'Never kill unknown process');pp_need(posix_kill($lease['pid'],15),'Own worker exactSIGTERM');$workers[]=$lease['pid'];}}
 foreach(['ai-cache','store-cache']as $name){$root=pp_private().'/'.$name;if(!is_dir($root))continue;pp_need(realpath($root)===$root&&!is_link($root),'Exact own cache root');$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root,FilesystemIterator::SKIP_DOTS),RecursiveIteratorIterator::CHILD_FIRST);foreach($it as $f){pp_need(!$f->isLink()&&strpos($f->getPathname(),$root.'/')===0,'No external cache links');if($f->isFile()){$removed[]=['path'=>$f->getPathname(),'sha256'=>hash_file('sha256',$f->getPathname())];pp_need(unlink($f->getPathname()),'Exact owned cache file removal');}elseif($f->isDir())rmdir($f->getPathname());}}
 pp_save('cleanup.json',['worker_SIGTERM'=>$workers,'only_own_cache_removed'=>$removed,'business_DELETE'=>0,'marked_business_rows_retained'=>true]);echo pp_json(['status'=>'OWN_WORKERS_CACHE_CLEANED','cache_files'=>count($removed),'workers'=>count($workers),'business_DELETE'=>0])."\n";exit;
}
try{
 pp_need(hash_file('sha256',pp_base().'/machine-plan.json')==='2cbf71e15720fb654b963bbea7f2556b2711177cd573e714670248e11cc5f1e5','Frozen exact granted machine scope');
 if($mode==='warm-store'||$mode==='warm-ai'){$ai=$mode==='warm-ai';$app=$ai?pp_ai():pp_store();$proof=[];foreach(['AI','ZHCT']as $db){$sql=getenv('PP_SIDE')==='B'?'SELECT DATABASE() schema_name':"SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') schema_name FROM DUAL";if($ai)$conn=$app->db->connect($db==='AI'?'mysql':'mysql_zhct');else $conn=$db==='AI'?get_ai_db():\think\Db::connect();$rows=$conn->query($sql);$rec=pp_material($rows);pp_need(count($rec['rows'])===1&&$rec['rows'][0]['schema_name']===getenv('POC_'.$db.'_SCHEMA'),'Actual original native two-client live identity');$proof[$db]=['original_connector'=>get_class($conn),'identity'=>$rec];}$proof['includes']=pp_includes($ai?'ai':'store');$proof['full_source']=pp_sources($ai?'ai':'store');pp_save($mode.'.json',$proof);}
 elseif($mode==='before'){pp_need(is_file(pp_private().'/warm-store.json')&&is_file(pp_private().'/warm-ai.json'),'Both real native client warms before prepare/Auth');pp_protect('before');$plan=pp_input('fresh-plan.json');foreach($plan['steps']as $s)if($s['role']==='collision')pp_need(pp_read($s['db'],$s['SQL'],$s['binds'],$s['label'])['rows']===[],'Exact new marker collision0');$s=array_values(array_filter($plan['steps'],static function($s){return $s['label']==='coffee.active';}))[0];$r=pp_read('ZHCT',$s['SQL'],$s['binds'],'actual-key-still-same')['rows'];pp_equal($r,pp_input('fresh-records.json')['coffee.active']['rows'],'Accepted unique real key row stable before new chain');pp_need(count($r)===1,'Exactly one accepted key');pp_save('before-complete.json',['protection'=>29,'marker_collision0'=>3,'actual_key_unchanged'=>true]);}
 elseif($mode==='prepare'){pp_need(is_file(pp_private().'/before-complete.json'),'Original protection/collision lease before prepare');$plan=json_decode(file_get_contents(pp_base().'/machine-plan.json'),true)['equipment'][getenv('PP_SIDE')];pp_need($plan['unknown_omitted_required']===[]&&count($plan['binds'])===14&&count($plan['PDO_types'])===14,'Actual approved14 bind/required scope');foreach($plan['binds']as $i=>$v)pp_need(gettype($v)===$plan['PHP_types'][$i],'Frozen literal PHP type');pp_save('prepare-attempt.json',['SQL'=>$plan['SQL'],'binds'=>$plan['binds'],'PHP_types'=>$plan['PHP_types'],'PDO_types'=>$plan['PDO_types'],'attempted_at'=>microtime(true)]);$pdo=pp_pdo('ZHCT');$s=$pdo->prepare($plan['SQL']);foreach($plan['binds']as $i=>$v)$s->bindValue($i+1,$v,$plan['PDO_types'][$i]);try{$ok=$s->execute();$id=$pdo->lastInsertId();pp_save('prepare-result.json',['success'=>$ok,'rowCount'=>$s->rowCount(),'errorInfo'=>$s->errorInfo(),'generated_ID'=>(int)$id,'native_ID_type'=>gettype($id)]);pp_need($ok&&$s->rowCount()===1&&(int)$id>0,'Exactly1 real generated equipment');pp_equipment();}catch(Throwable $e){pp_save('prepare-error.json',['class'=>get_class($e),'message'=>$e->getMessage(),'errorInfo'=>$s->errorInfo(),'unknown_or_failed_no_replay'=>true]);throw $e;}}
 elseif($mode==='auth'){pp_need(is_file(pp_private().'/equipment.json')&&is_file(pp_private().'/workers.json'),'Mint only after source/warm/equipment/workers ready');$token='CDXPPFORM11_'.getenv('PP_SIDE').'_'.bin2hex(random_bytes(24));pp_save('auth-attempt.json',['token_sha256'=>hash('sha256',$token),'TTL'=>300,'at'=>time()]);$_SERVER['HTTP_HOST']='prepay.code-scan.invalid';$_SERVER['HTTP_PLATFORM']='POC';$app=pp_ai();$id=pp_input('baseline.json')['ids']['AI_U1'];$profile=['user'=>['user_id'=>$id],'password_version'=>0,'login_type'=>'thirdparty'];pp_need($app->cache->set($token,$profile,300),'Original FileCache own token create');$file=$app->cache->store('file')->getCacheKey($token);pp_need(strpos($file,pp_private().'/ai-cache/')===0&&is_file($file),'Exact own original FileCache file');pp_save('token.json',['token'=>$token,'profile'=>$profile,'TTL'=>300,'cache_file'=>$file,'created_at'=>time(),'original_file_sha256'=>hash_file('sha256',$file)]);$user=\app\api\model\User::getUserByToken($token);pp_need((int)$user['user_id']===$id&&(int)$user['store_id']===2147001111,'Actual original UserModel authorization identity/tenant');pp_save('auth-proven.json',['user_id'=>$id,'store_id'=>2147001111,'original_UserModel'=>true,'included'=>pp_includes('ai')]);}
 elseif($mode==='dispatch'){$accepted=pp_input('accepted-signature.json');pp_need(is_file(pp_private().'/auth-proven.json')&&!is_file(pp_private().'/send-attempt-code.json'),'Only one dispatch before any attempt');$fields=$accepted['ordered_fields'];$fields['timestamp']=(string)time();$fields['randstr']=bin2hex(random_bytes(16));$sort=[$accepted['effective_appkey'],$fields['timestamp'],$fields['randstr']];sort($sort,SORT_STRING);$fields['sign']=sha1(implode('',$sort));foreach($accepted['ordered_fields']as $k=>$v)if(!in_array($k,['timestamp','randstr','sign'],true))pp_need($fields[$k]===$v,'Only dynamic signature triplet');pp_save('DISPATCH_1.json',['ordered_fields'=>$fields,'body'=>http_build_query($fields,'','&',PHP_QUERY_RFC1738),'created_at'=>time(),'tool_lease'=>60,'server_TTL'=>'NONE_IN_SOURCE']);}
 elseif($mode==='code-checkpoint'){pp_code_checkpoint();}
 elseif($mode==='clock-scan'){pp_need(is_file(pp_private().'/code-checkpoint.json'),'Code physically proven before scan wait');pp_save('scan-wait-attempt.json',['milliseconds'=>1100,'at'=>microtime(true)]);usleep(1100000);$clock=pp_clock();$code=pp_saved('code-checkpoint.json');pp_save('scan-clock.json',['clock0'=>$clock]);pp_need($clock>$code['full']['rows'][0]['update_time'],'One same-DB clock0 strictly greater than codeUT; no polling/replay');$fields=['type'=>'200','torderid'=>(string)$code['id']];pp_save('scan-request.json',['fields'=>$fields,'body'=>json_encode($fields,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)]);}
 elseif($mode==='scan-checkpoint'){pp_scan_checkpoint();}
 elseif($mode==='send-code'||$mode==='send-scan'){$phase=substr($mode,5);$side=getenv('PP_SIDE');$request=pp_saved($phase==='code'?'DISPATCH_1.json':'scan-request.json');if($phase==='code')pp_need(time()-$request['created_at']<=60,'Only immutable DISPATCH_1 tool lease60s');else pp_need(time()-pp_saved('token.json')['created_at']<295,'Original token safely withinTTL300');$port=$side==='B'?($phase==='code'?19091:19093):($phase==='code'?19092:19094);$path=$phase==='code'?'/api/prepayOrder/code':'/api/PrepayOrder/scan';$headers=['Host: prepay.code-scan.invalid','Content-Type: '.($phase==='code'?'application/x-www-form-urlencoded':'application/json'),'Connection: close'];if($phase==='scan'){$headers[]='platform: POC';$headers[]='Access-Token: '.pp_saved('token.json')['token'];}pp_save('send-attempt-'.$phase.'.json',['method'=>'POST','port'=>$port,'path'=>$path,'body_sha256'=>hash('sha256',$request['body']),'at'=>microtime(true),'no_replay_after_this_point'=>true]);$opts=['http'=>['method'=>'POST','header'=>implode("\r\n",$headers),'content'=>$request['body'],'timeout'=>60,'ignore_errors'=>true,'follow_location'=>0,'max_redirects'=>0]];$body=file_get_contents('http://127.0.0.1:'.$port.$path,false,stream_context_create($opts));pp_save('client-response-'.$phase.'.json',['body'=>$body,'headers'=>$http_response_header??[],'received_at'=>microtime(true)]);pp_need($body!==false&&is_file(pp_private().'/response-'.$phase.'.json'),'Original response preserved before sending');pp_need($body===pp_saved('response-'.$phase.'.json')['body'],'Wire original bytes equal saved application response');}
 else throw new RuntimeException('Unknown exact CLI phase');
 echo pp_json(['status'=>'PHASE_COMPLETED','phase'=>$mode,'side'=>getenv('PP_SIDE'),'budget'=>is_file(pp_private().'/budget.json')?pp_saved('budget.json'):null])."\n";
}catch(Throwable $e){pp_event(['event'=>'phase-stopped','mode'=>$mode,'class'=>get_class($e),'message'=>$e->getMessage(),'line'=>$e->getLine(),'no_success_or_unknown_replay'=>true]);fwrite(STDERR,pp_json(['status'=>'STOPPED_KEEP_ORIGINAL','phase'=>$mode,'class'=>get_class($e),'message'=>$e->getMessage(),'line'=>$e->getLine()])."\n");exit(1);}
