<?php

declare(strict_types=1);

$lane=(string)($argv[1]??'');$mode=(string)($argv[2]??'');
$self=$lane==='B'?(string)hash_file('sha256',__FILE__):'';
if(count($argv)!==3||!in_array($lane,['B','C'],true)
    ||!in_array($mode,['--preflight','--execute','--audit'],true)
    ||($mode==='--execute'&&((string)getenv('CDX_AC9_APPROVE')!=='ROOT_ARCHIVE_CRUD9_V1'
        ||($lane==='B'?!hash_equals($self,(string)getenv('CDX_AC9_SHA'))
            :(string)getenv('CDX_AC9_SOURCE_CHECKED')!=='1')))){
    echo json_encode(['status'=>'default_deny','connected'=>false,'http_sent'=>false,'dml'=>false]),PHP_EOL;exit(78);
}
$stage='bootstrap';
set_exception_handler(static function(Throwable$e)use(&$stage):void{
    echo json_encode(['status'=>'redacted_stop','stage'=>$stage,'class'=>get_class($e),
        'code'=>(string)$e->getCode(),'message_sha'=>hash('sha256',$e->getMessage())]),PHP_EOL;exit(2);
});
if($lane==='B'){
    $statePath='/tmp/cdx-rpe-b-worker.state';
    if(!is_file($statePath)||is_link($statePath)||(fileperms($statePath)&0777)!==0600)
        throw new RuntimeException('B private worker state absent');
    $state=parse_ini_file($statePath,false,INI_SCANNER_RAW);
    $root=(string)($state['root']??'');$pid=(int)($state['pid']??0);$port=(int)($state['port']??0);
    if(!preg_match('~^/tmp/cdx-rpe-b-runtime\.[A-Za-z0-9]+$~D',$root)||is_link($root)||$pid<=0||$port!==18082)
        throw new RuntimeException('B private worker state invalid');
}else{$root='/tmp/zhct-dm-poc-20260928.fcpiiN/store';$pid=112175;$port=18080;}
$base='http://127.0.0.1:'.$port;
$runtimeReady=static function()use($lane,$pid,$port,$root,$base):bool{
    if($lane==='B'){$cmd=(string)shell_exec('/bin/ps -p '.$pid.' -o command=');
        $owner=trim((string)shell_exec('/usr/sbin/lsof -nP -t -iTCP:'.$port.' -sTCP:LISTEN 2>/dev/null'));
        $process=$owner===(string)$pid&&strpos($cmd,'-S 127.0.0.1:'.$port)!==false&&strpos($cmd,$root.'/public')!==false;
    }else{$cmd=(string)@file_get_contents('/proc/'.$pid.'/cmdline');
        $children=trim((string)@file_get_contents('/proc/'.$pid.'/task/'.$pid.'/children'));
        $process=strpos($cmd,$root.'/public')!==false&&strpos($cmd,'127.0.0.1:'.$port)!==false&&$children==='';}
    $b=json_decode((string)@file_get_contents($base.'/__poc_boundary'),true);
    return$process&&is_array($b)&&($b['external_stubs']??null)===true
        &&($b['redis_isolated']??null)===true&&($b['real_queue']??true)===false;
};
if(!$runtimeReady())throw new RuntimeException('HTTP boundary drift');
$hashes=[
'application/p/controller/NationalHistory.php'=>'3eab69c12c7776433f5e772625c4227a5ecbfba54ac0521ec57d204239bb8c4d',
'application/p/controller/PhysicalMature.php'=>'a56042454db4ff6fc7811444eb02883e00cda276b899688c7e5f43708c7f699b',
'application/p/controller/ProfessionEvaluation.php'=>'8a270a924da649e9ae1ec26718c86cec91d26d60e891b246efbd75d8fd7cc546',
'application/p/logic/NationalHistory.php'=>'3cbafdff4314877462647087a45be9f436b0df35dc44a8cee099ec56ed41c05a',
'application/p/logic/PhysicalMature.php'=>'bd2296eb9567f74633f13c9334e119d9e43e1c5e7be355a8c9357b4272009571',
'application/p/logic/ProfessionEvaluation.php'=>'43b9abc0b6d99f14f5b88c5fe9ccfc620155cc4fdc93673e69b9ead017a320f7',
'application/model/NationalHistory.php'=>'57212ad18a76f3a2ddbdac60577f6de267e8e74cc40d451deefc0e55d40db5a9',
'application/model/PhysicalMature.php'=>'78cd2fad8cbcdbf331b0d3553c936581c868ba57d2a6eceffe0acc533bb69bb4',
'application/model/ProfessionEvaluation.php'=>'1371f12db0c73a6eeaf565ed56e2da44471177f9d31185318b3e4e704243300d',
'application/validate/NationalHistory.php'=>'7f5299d4d5e649b93494b368617eb30c636aab49df6509a1345cc77caec44448',
'application/validate/PhysicalMature.php'=>'0a65024157513647be070383ff1e547d3edcf45cc6f0c208fc4b5d32a2805cf8',
'application/validate/ProfessionEvaluation.php'=>'9105ccc772695eced3464f6bdbaa7bcc4c3af096d022e9f9b5018036ffa3a424',
'application/model/BaseModel.php'=>'439740d6cf118e4541dfa719e120afd95979c497e7639f43d8efe01e6a5d3596',
'application/model/Staff.php'=>'e709b91af8e78758b0adbb29697dba4d16d62402d8c365712afe9c47e72277d3',
'application/base/AdminController.php'=>'7565b36fa4dda2c21cc4fa3b37753dbffb7c3a464bb8c11ea0f17ca00bececa5',
'application/base/Security.php'=>'b82e5ed982e6084a2b2942c033d4767428fb6f1012ba628f609477a7563eb4c3'];
foreach($hashes as$path=>$sha)if(!is_file($root.'/'.$path)||is_link($root.'/'.$path)
    ||hash_file('sha256',$root.'/'.$path)!==$sha)throw new RuntimeException('Business source drift');
$stage='database-boundary';
if($lane==='B'){$cfg=require'/Users/wiscourper/Documents/workspace/zhct/zhctproject/store/application/config/local/database.php';
    if(!is_array($cfg)||(int)($cfg['hostport']??3306)!==3306
        ||hash_file('sha256',$root.'/application/database.php')!=='6a64b60c0c4f9da3856ea2a0a39a828609a6d73053b2946b0459d28e7c2a5216')
        throw new RuntimeException('B database config drift');
    $process=' '.(string)shell_exec('/bin/ps eww -p '.$pid.' -o command=').' ';
    foreach(['hostname'=>'POC_HOST','hostport'=>'POC_PORT','database'=>'POC_SCHEMA','username'=>'POC_USER','password'=>'POC_PASSWORD']as$key=>$env){
        $expected=(string)($cfg[$key]??($key==='hostport'?'3306':''));
        if($expected===''||strpos($process,' '.$env.'='.$expected.' ')===false)throw new RuntimeException('B worker DB drift');}
    $dsn='mysql:host='.$cfg['hostname'].';port='.(int)($cfg['hostport']??3306).';dbname='.$cfg['database'].';charset='.($cfg['charset']??'utf8');
}else{$worker=[];foreach(explode("\0",(string)file_get_contents('/proc/'.$pid.'/environ'))as$entry){$pair=explode('=',$entry,2);if(count($pair)===2)$worker[$pair[0]]=$pair[1];}
    foreach(['POC_HOST'=>'127.0.0.1','POC_PORT'=>'5237','POC_SCHEMA'=>'ZHCT_APP','POC_USER'=>'ZHCT_APP','POC_DIALECT'=>'dm']as$key=>$value)
        if((string)($worker[$key]??'')!==$value)throw new RuntimeException('C worker DB drift');
    $cfg=require$root.'/application/database.php';$dsn='dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';}
$connect=static function()use($dsn,$cfg):PDO{return new PDO($dsn,(string)$cfg['username'],(string)$cfg['password'],
    [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_CASE=>PDO::CASE_LOWER,PDO::ATTR_TIMEOUT=>5]);};
$db=$connect();$identity=$lane==='B'?(string)$db->query("SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())")->fetchColumn()
    :'ZHCT_APP|5237|'.(string)$db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn();
$identitySha=$lane==='B'?'003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401':'bc98485aed26beab348770a82ae38dbf922b04ab88a210cd7282c4caf0156194';
if(hash('sha256',$identity)!==$identitySha)throw new RuntimeException('DB identity drift');
$tables=$lane==='B'?['user'=>'ydy_user','staff'=>'ydy_staff','national'=>'ydy_national_history','physical'=>'ydy_physical_mature','profession'=>'ydy_profession_evaluation']
    :['user'=>'YDY_USER','staff'=>'YDY_STAFF','national'=>'YDY_NATIONAL_HISTORY','physical'=>'YDY_PHYSICAL_MATURE','profession'=>'YDY_PROFESSION_EVALUATION'];
$read=static function(PDO$p,string$sql,array$args=[],int$cap=100):array{$s=$p->prepare($sql);$s->execute($args);$out=[];while(($r=$s->fetch(PDO::FETCH_ASSOC))!==false){if(count($out)>=$cap)throw new RuntimeException('row cap');$clean=[];foreach(array_change_key_case($r,CASE_LOWER)as$k=>$v)$clean[$k]=is_resource($v)?stream_get_contents($v):$v;ksort($clean);$out[]=$clean;}return$out;};
$count=static function(PDO$p,string$sql,array$args=[])use($read):int{$r=$read($p,$sql,$args,1);return(int)(reset($r[0])?:0);};
$required=['user'=>['ID','UUID','ACCOUNT','PWD','SALT','NAME','TYPE','STATUS','CREATE_TIME','CREATE_BY','IS_DELETE'],
'staff'=>['ID','UUID','STATION_UUID','IS_ATHLETE','GRADE','NAME','SEX','BIRTHDAY','HEIGHT','WEIGHT','SPORT_UUID','SPORT_EVENT_UUID','IN_TIME','CREATE_TIME','CREATE_BY','PERSONNEL_UMBER','IS_SHOW','STATUS','PERMANENT_ADDRESS','COACH_NAME','SPORT_YEAR'],
'national'=>['ID','UUID','STAFF_UUID','TEAM_NAME','TEAM_COACH','IN_TEAM_DATE','OUT_TEAM_DATE','DEMO','CREATE_TIME','CREATE_BY'],
'physical'=>['ID','UUID','STAFF_UUID','TIME','HEIGHT','WEIGHT','FINGER_SPAN','LUNG','CREATE_TIME','CREATE_BY'],
'profession'=>['ID','UUID','STAFF_UUID','PROFESSION','TIME','DEMO','CREATE_TIME','CREATE_BY']];
$metadata=[];$stage='metadata';
foreach($required as$logical=>$columns){if($lane==='B'){$s=$db->prepare('SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? ORDER BY ORDINAL_POSITION');$s->execute([$tables[$logical]]);}else{$s=$db->prepare('SELECT COLUMN_NAME,DATA_TYPE,DATA_LENGTH,DATA_PRECISION,DATA_SCALE,NULLABLE,DATA_DEFAULT FROM USER_TAB_COLUMNS WHERE TABLE_NAME=? ORDER BY COLUMN_ID');$s->execute([$tables[$logical]]);}$names=[];foreach($s->fetchAll(PDO::FETCH_ASSOC)as$row){$names[]=strtoupper((string)$row['column_name']);$metadata[]=[$logical,$row];}foreach($columns as$column)if(!in_array($column,$names,true))throw new RuntimeException('Required column absent');}
$physicalNames=array_values($tables);
if($lane==='B'){$marks=implode(',',array_fill(0,count($physicalNames),'?'));$s=$db->prepare('SELECT COUNT(*) FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_SCHEMA=DATABASE() AND EVENT_OBJECT_TABLE IN ('.$marks.')');$s->execute($physicalNames);$trigger=(int)$s->fetchColumn();$s=$db->prepare('SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA=DATABASE() AND (TABLE_NAME IN ('.$marks.') OR REFERENCED_TABLE_NAME IN ('.$marks.'))');$s->execute(array_merge($physicalNames,$physicalNames));$fk=(int)$s->fetchColumn();}else{$quoted="'".implode("','",$physicalNames)."'";$trigger=(int)$db->query("SELECT COUNT(*) FROM USER_TRIGGERS WHERE TABLE_NAME IN ($quoted)")->fetchColumn();$fk=(int)$db->query("SELECT COUNT(*) FROM USER_CONSTRAINTS WHERE CONSTRAINT_TYPE='R' AND TABLE_NAME IN ($quoted)")->fetchColumn();}
if($trigger||$fk)throw new RuntimeException('Unreviewed FK/trigger');
$refTables=static function(PDO$p)use($lane):array{$s=$lane==='B'?$p->query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND COLUMN_NAME='staff_uuid'"):$p->query("SELECT TABLE_NAME FROM USER_TAB_COLUMNS WHERE COLUMN_NAME='STAFF_UUID'");return$s->fetchAll(PDO::FETCH_COLUMN);};
$staffRefTables=$refTables($db);if(!$staffRefTables||count($staffRefTables)>200)throw new RuntimeException('Reference inventory');
$refs=static function(PDO$p,array$refTables,string$value)use($count):array{$out=[];foreach($refTables as$table){if(!preg_match('/^YDY_[A-Z0-9_]+$/i',(string)$table))throw new RuntimeException('Ref table');$n=$count($p,'SELECT COUNT(*) FROM '.$table.' WHERE STAFF_UUID=?',[$value]);if($n)$out[(string)$table]=$n;}return$out;};
$markerCount=static function(PDO$p)use($count,$tables):int{return$count($p,'SELECT COUNT(*) FROM '.$tables['user']." WHERE UUID LIKE 'CDXAC9%' OR ACCOUNT LIKE 'CDXAC9%' OR CREATE_BY LIKE 'CDXAC9%'")+$count($p,'SELECT COUNT(*) FROM '.$tables['staff']." WHERE UUID LIKE 'CDXAC9%' OR PERSONNEL_UMBER LIKE 'CDXAC9%' OR CREATE_BY LIKE 'CDXAC9%'")+$count($p,'SELECT COUNT(*) FROM '.$tables['national']." WHERE STAFF_UUID LIKE 'CDXAC9%' OR CREATE_BY LIKE 'CDXAC9%'")+$count($p,'SELECT COUNT(*) FROM '.$tables['physical']." WHERE STAFF_UUID LIKE 'CDXAC9%' OR CREATE_BY LIKE 'CDXAC9%'")+$count($p,'SELECT COUNT(*) FROM '.$tables['profession']." WHERE STAFF_UUID LIKE 'CDXAC9%' OR CREATE_BY LIKE 'CDXAC9%'");};
if($mode==='--preflight'){$old=$markerCount($db);echo json_encode(['status'=>$old===0?'select_only_ready':'marker_stop','lane'=>$lane,'metadata_sha'=>hash('sha256',serialize($metadata)),'foreign_keys'=>$fk,'triggers'=>$trigger,'old_marker_rows'=>$old,'staff_ref_tables'=>count($staffRefTables),'http_sent'=>false,'dml'=>false]),PHP_EOL;exit($old===0?0:2);}
if($mode==='--audit'){$journal=(string)getenv('CDX_AC9_JOURNAL');if(!preg_match('~^/tmp/cdx-ac9-[bc]-[a-f0-9]{12}/recovery\.json$~D',$journal)||!is_file($journal)||is_link($journal)||is_link(dirname($journal))||(fileperms(dirname($journal))&0777)!==0700||(fileperms($journal)&0777)!==0600)throw new RuntimeException('Audit journal');$saved=json_decode((string)file_get_contents($journal),true);if(!is_array($saved)||($saved['lane']??null)!==$lane||($saved['phase']??null)!=='cleaned'||!preg_match('/^CDXAC9[A-F0-9]{12}$/D',(string)($saved['marker']??'')))throw new RuntimeException('Audit ownership');$fresh=$connect();if($markerCount($fresh)!==0||$refs($fresh,$staffRefTables,(string)$saved['staff_uuid']))throw new RuntimeException('Audit not zero');unlink($journal);rmdir(dirname($journal));echo json_encode(['status'=>'independent_zero_pass','lane'=>$lane,'marker_rows'=>0,'staff_references'=>0,'private_journal_removed'=>true]),PHP_EOL;exit(0);}
if($markerCount($db)!==0)throw new RuntimeException('Old marker');
$marker='CDXAC9'.strtoupper(bin2hex(random_bytes(6)));$actorUuid=$marker.'U';$staffUuid=$marker.'S';
$dir='/tmp/cdx-ac9-'.strtolower($lane).'-'.strtolower(bin2hex(random_bytes(6)));if(file_exists($dir)||!mkdir($dir,0700)||!chmod($dir,0700))throw new RuntimeException('Private dir');$journal=$dir.'/recovery.json';$saved=['lane'=>$lane,'marker'=>$marker,'staff_uuid'=>$staffUuid,'phase'=>'prepared','ids'=>[]];$save=static function()use(&$saved,$journal):void{$e=json_encode($saved);if(file_put_contents($journal,$e,LOCK_EX)!==strlen($e)||!chmod($journal,0600))throw new RuntimeException('Journal');};$save();
$insert=static function(PDO$p,string$table,array$data):void{$cols=array_keys($data);$s=$p->prepare('INSERT INTO '.$table.' ('.implode(',',$cols).') VALUES ('.implode(',',array_fill(0,count($cols),'?')).')');$s->execute(array_values($data));if($s->rowCount()!==1)throw new RuntimeException('Insert');};
$find=static function(PDO$p,string$table,array$where)use($read):array{$parts=[];foreach(array_keys($where)as$key)$parts[]=$key.'=?';$rows=$read($p,'SELECT * FROM '.$table.' WHERE '.implode(' AND ',$parts),array_values($where),2);if(count($rows)!==1)throw new RuntimeException('Ownership');return$rows[0];};
$shape=null;$shape=static function($v)use(&$shape){if(!is_array($v))return gettype($v);if($v===[])return[];$keys=array_keys($v);if($keys===range(0,count($v)-1))return['[]'=>$shape($v[0])];$out=[];foreach($v as$k=>$x)$out[(string)$k]=$shape($x);ksort($out);return$out;};
$evidence=static function(array$b)use($shape):array{return['key_sha'=>hash('sha256',serialize(array_keys($b))),'type_sha'=>hash('sha256',serialize($shape($b))),'shape'=>$shape($b)];};
$uncertain=false;$request=static function(string$path,array$form,?string$token)use($base,$runtimeReady,&$uncertain):array{if(!$runtimeReady())throw new RuntimeException('Boundary');$body=http_build_query($form,'','&',PHP_QUERY_RFC3986);$headers="Content-Type: application/x-www-form-urlencoded\r\nContent-Length: ".strlen($body)."\r\n".($token===null?'':'token: '.$token."\r\n");$uncertain=true;$stream=@fopen($base.$path,'rb',false,stream_context_create(['http'=>['method'=>'POST','header'=>$headers,'content'=>$body,'timeout'=>20,'ignore_errors'=>true]]));$raw=is_resource($stream)?stream_get_contents($stream,1048577):false;$meta=is_resource($stream)?stream_get_meta_data($stream):[];$hs=$http_response_header??[];if(is_resource($stream))fclose($stream);preg_match('/HTTP\/\S+\s+(\d+)/',(string)($hs[0]??''),$m);$within=is_string($raw)&&strlen($raw)<=1048576;$json=$within?json_decode($raw,true):null;if(!isset($m[1])||(int)$m[1]!==200||!empty($meta['timed_out'])||!$within||!is_array($json)||json_last_error()!==JSON_ERROR_NONE||!array_key_exists('code',$json))throw new RuntimeException('HTTP unknown');$uncertain=false;return$json;};
$fixture=false;$failure=null;$result=['status'=>'FAIL','lane'=>$lane,'cases'=>[],'rejections'=>[]];$now=date('Y-m-d H:i:s');
try{$stage='fixture';$db->beginTransaction();$insert($db,$tables['user'],['UUID'=>$actorUuid,'ACCOUNT'=>$marker,'PWD'=>'DISABLED','SALT'=>strtoupper(bin2hex(random_bytes(8))),'NAME'=>$marker,'TYPE'=>0,'STATUS'=>0,'CREATE_TIME'=>$now,'CREATE_BY'=>$marker,'IS_DELETE'=>0]);$insert($db,$tables['staff'],['UUID'=>$staffUuid,'STATION_UUID'=>'0','IS_ATHLETE'=>1,'GRADE'=>1,'NAME'=>$marker,'SEX'=>1,'BIRTHDAY'=>'2000-01-01','HEIGHT'=>'170.00','WEIGHT'=>'60.00','NATION'=>'测试','NATIVE_PLACE'=>'测试','IDENTITY_TYPE'=>1,'IDENTITY_NUMBER'=>$marker,'HEAD_IMG'=>$marker,'SPORT_UUID'=>'0','SPORT_EVENT_UUID'=>'[]','IN_TIME'=>'2020-01-01','CREATE_TIME'=>$now,'CREATE_BY'=>$marker,'PERSONNEL_UMBER'=>substr($marker,-8),'IS_SHOW'=>0,'STATUS'=>0,'PERMANENT_ADDRESS'=>'测试地址','COACH_NAME'=>'测试教练','SPORT_YEAR'=>'1']);$actor=$find($db,$tables['user'],['UUID'=>$actorUuid,'ACCOUNT'=>$marker,'CREATE_BY'=>$marker]);$staff=$find($db,$tables['staff'],['UUID'=>$staffUuid,'CREATE_BY'=>$marker]);$saved['ids']=['actor'=>(int)$actor['id'],'staff'=>(int)$staff['id']];$db->commit();$fixture=true;$saved['phase']='fixture_committed';$save();require_once$root.'/application/base/Security.php';$token=\app\base\Security::encrypt(implode("\t",[(string)$saved['ids']['actor'],$actorUuid,$marker,'0','','',$actorUuid]));
$modules=[
'nationalHistory'=>['path'=>'/p/NationalHistory','table'=>'national','marker'=>'team_name','add'=>['staff_uuid'=>$staffUuid,'team_name'=>$marker.'NA','team_coach'=>'测试教练','in_team_date'=>'2001-01-02','out_team_date'=>'2002-02-03','demo'=>'中文备注'],'update'=>['staff_uuid'=>$staffUuid,'team_name'=>$marker.'NU','team_coach'=>'更新教练','in_team_date'=>'2001-01-03','out_team_date'=>'2002-02-04','demo'=>'更新备注'],'invalid'=>'team_name'],
'physicalMature'=>['path'=>'/p/physicalMature','table'=>'physical','marker'=>null,'add'=>['staff_uuid'=>$staffUuid,'time'=>'2003-03-04','height'=>171,'weight'=>61,'finger_span'=>172,'lung'=>4001],'update'=>['time'=>'2003-03-05','height'=>172,'weight'=>62,'finger_span'=>173,'lung'=>4002],'invalid'=>'height'],
'professionEvaluation'=>['path'=>'/p/ProfessionEvaluation','table'=>'profession','marker'=>'profession','add'=>['staff_uuid'=>$staffUuid,'profession'=>$marker.'PA','time'=>'2005-05-06','demo'=>'中文说明'],'update'=>['staff_uuid'=>$staffUuid,'profession'=>$marker.'PU','time'=>'2005-05-07','demo'=>'更新说明'],'invalid'=>'profession']];
foreach($modules as$name=>$m){$stage=$name.'-unauth';foreach(['add'=>$m['add'],'update'=>array_merge(['uuid'=>$marker.'X'],$m['update']),'delete'=>['uuid'=>$marker.'X']]as$action=>$form){$body=$request($m['path'].'/'.$action,$form,null);if((int)($body['code']??0)===0)throw new RuntimeException('Unauth accepted');$result['rejections'][$name.'.'.$action.'.unauth']=true;}
$invalid=$m['add'];unset($invalid[$m['invalid']]);$body=$request($m['path'].'/add',$invalid,$token);if((int)($body['code']??0)===0)throw new RuntimeException('Invalid accepted');$result['rejections'][$name.'.add.required']=true;
$stage=$name.'-add';$body=$request($m['path'].'/add',$m['add'],$token);if((int)($body['code']??-1)!==0)throw new RuntimeException('Add failed');$where=['STAFF_UUID'=>$staffUuid,'CREATE_BY'=>$actorUuid];if($m['marker']!==null)$where[strtoupper($m['marker'])]=$m['add'][$m['marker']];$row=$find($connect(),$tables[$m['table']],$where);$id=(int)$row['id'];$uuid=rtrim((string)$row['uuid']);if($id<=0||$uuid==='')throw new RuntimeException('Add identity');foreach($m['add']as$key=>$value)if($key!=='staff_uuid'&&(string)$row[$key]!=(string)$value)throw new RuntimeException('Add readback');$result['cases'][$name.'.add']=array_merge($evidence($body),['db_write'=>true]);
$stage=$name.'-update';$update=array_merge(['uuid'=>$uuid],$m['update']);$body=$request($m['path'].'/update',$update,$token);if((int)($body['code']??-1)!==0)throw new RuntimeException('Update failed');$rows=$read($connect(),'SELECT * FROM '.$tables[$m['table']].' WHERE ID=? AND UUID=?',[$id,$uuid],2);if(count($rows)!==1)throw new RuntimeException('Update identity');foreach($m['update']as$key=>$value)if($key!=='staff_uuid'&&(string)$rows[0][$key]!=(string)$value)throw new RuntimeException('Update readback');$result['cases'][$name.'.update']=array_merge($evidence($body),['same_row_updated'=>true]);
$stage=$name.'-delete';$body=$request($m['path'].'/delete',['uuid'=>$uuid],$token);if((int)($body['code']??-1)!==0||$count($connect(),'SELECT COUNT(*) FROM '.$tables[$m['table']].' WHERE ID=? AND UUID=?',[$id,$uuid])!==0)throw new RuntimeException('Delete readback');$result['cases'][$name.'.delete']=array_merge($evidence($body),['deleted_owned_row'=>1]);}
$result['status']='HTTP_PASS_PENDING_CLEANUP';}catch(Throwable$e){if($db->inTransaction())$db->rollBack();$failure=['stage'=>$stage,'class'=>get_class($e),'code'=>(string)$e->getCode(),'message_sha'=>hash('sha256',$e->getMessage())];}
if(!$fixture){if($markerCount($connect())===0){unlink($journal);rmdir($dir);}$result['status']='FIXTURE_FAILED_ROLLBACK';$result['failure']=$failure;echo json_encode($result),PHP_EOL;exit(2);}if($uncertain||!$runtimeReady()){$saved['phase']='unknown_http_retain';$save();echo json_encode(['status'=>'unknown_http_retain_fixture','journal'=>$journal]),PHP_EOL;exit(3);}
$allRefs=$refs($connect(),$staffRefTables,$staffUuid);foreach(['national','physical','profession']as$logical){$key=$tables[$logical];$n=(int)($allRefs[$key]??0);if($n>1){$saved['phase']='unexpected_reference_retain';$save();echo json_encode(['status'=>'unexpected_reference_retain_fixture','journal'=>$journal]),PHP_EOL;exit(4);}unset($allRefs[$key]);}if($allRefs){$saved['phase']='unexpected_reference_retain';$save();echo json_encode(['status'=>'unexpected_reference_retain_fixture','journal'=>$journal]),PHP_EOL;exit(4);}
$clean=$connect();$clean->beginTransaction();try{foreach(['national','physical','profession']as$logical){$s=$clean->prepare('DELETE FROM '.$tables[$logical].' WHERE STAFF_UUID=? AND CREATE_BY=?');$s->execute([$staffUuid,$actorUuid]);if($s->rowCount()>1)throw new RuntimeException('Archive cleanup scope');}$s=$clean->prepare('DELETE FROM '.$tables['staff'].' WHERE ID=? AND UUID=? AND CREATE_BY=? AND IS_SHOW=0 AND STATUS=0');$s->execute([$saved['ids']['staff'],$staffUuid,$marker]);if($s->rowCount()!==1)throw new RuntimeException('Staff cleanup');$s=$clean->prepare('DELETE FROM '.$tables['user'].' WHERE ID=? AND UUID=? AND ACCOUNT=? AND CREATE_BY=? AND TYPE=0 AND STATUS=0');$s->execute([$saved['ids']['actor'],$actorUuid,$marker,$marker]);if($s->rowCount()!==1)throw new RuntimeException('Actor cleanup');$clean->commit();}catch(Throwable$e){if($clean->inTransaction())$clean->rollBack();$saved['phase']='cleanup_failed';$save();throw$e;}
$fresh=$connect();if($markerCount($fresh)!==0||$refs($fresh,$staffRefTables,$staffUuid))throw new RuntimeException('Cleanup not zero');$saved['phase']='cleaned';$save();$result['cleanup']=['marker_rows'=>0,'staff_references'=>0,'journal'=>$journal];if($failure===null&&count($result['cases'])===9&&count($result['rejections'])===12){$result['status']='HTTP_PASS_CLEANED_PENDING_AUDIT';echo json_encode($result,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),PHP_EOL;exit(0);}$result['status']='HTTP_FAIL_CLEANED';$result['failure']=$failure;echo json_encode($result,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),PHP_EOL;exit(2);
