<?php
declare(strict_types=1);require __DIR__.'/bootstrap.php';
$check(hash_file('sha256',__DIR__.'/case-proposal.json')==='51c59365391ea18d43c633b654a492a4cedddb9c5d78652bfbb95f3375fa8263','Root-approved exact26 case proposal');
$final=getenv('READ12_STAGE')==='run-final';$phase=$final?'FINAL':'original';
$check($final||!file_exists($runtime.'/run-started.json'),'Original historical phase already executed');
$check(!file_exists($runtime.'/run-'.$phase.'-started.json'),'No HTTP phase replay');
$lock=fopen($runtime.'/run.lock','c');$check(flock($lock,LOCK_EX|LOCK_NB),'Serial same-lane run');
$check($own()===$fixture['after'],'Full42 batch before exactly prepared original state');
$enumBefore=$read('SELECT * FROM yoshop_config_enum WHERE enum_type IN (6,7,8,9,10,11) AND is_delete=0 ORDER BY enum_type,'.($dm?'"ORDER"':'`order`'));
if($dm)$check((int)$read("SELECT COUNT(*) n FROM USER_OBJECTS WHERE OBJECT_NAME='SP_TABLEDEF'")[0]['n']===0,'No local metadata routine shadow');
$app=read12App($root,$runtime,'AUTH_PREPARATION'.($final?'_FINAL':''));$cache=new \think\cache\driver\File($app,['path'=>$runtime.'/cache/','prefix'=>'','expire'=>0]);$tokens=[];
foreach($tenants as $m=>$t){$old=array_values(array_filter($fixture['before']['store_user'],static function($r)use($t){return (int)$r['store_id']===$t;}));$check(count($old)===1,'One exact original marked operator');$class='app\\'.$m.'\\model\\store\\User';$model=$class::withoutGlobalScope()->where('store_user_id','=',(int)$old[0]['store_user_id'])->where('store_id','=',$t)->find();$check($model!==null,'Actual original Auth principal');$profile=$model->toArray();$check(!array_key_exists('password',$profile)&&(int)$profile['is_super']===1&&(int)$profile['store_id']===$t,'Actual original profile/tenant/super');$tokens[$m]=bin2hex(random_bytes(24));$cache->set($tokens[$m],['user'=>$profile,'store_id'=>$t,'is_login'=>true],3600);}
$proposal=json_decode(file_get_contents(__DIR__.'/case-proposal.json'),true);$cases=[];
foreach($proposal['cases'] as $case){if($final&&!($case['context']==='store'&&in_array($case['name'],['STAFF_DETAIL','STAFF_LIST','FOOD_DETAIL'],true)||$case['context']==='terminal'&&$case['name']==='STAFF_DETAIL'))continue;$scenario='PILOT_RR_'.($final?'FINAL_':'').strtoupper($case['context'].'_'.$case['name']);$body=$case['body'];foreach($body as &$value)if(is_string($value)&&strpos($value,'@')===0){$check(isset($fixture['refs'][$value]),'Body reference actual owned original key');$value=$fixture['refs'][$value];}unset($value);$case['scenario']=$scenario;$case['auth']=$case['auth']??true;$case['host']=$case['context'].'.remaining-read.invalid';$case['body']=$body;$case['body_raw']=json_encode((object)$body,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);$cases[$scenario]=$case;}
$check(count($cases)===($final?4:26),'Exact unique approved cases');$persist($final?'cases-FINAL.json':'cases.json',$cases);$persist('run-'.$phase.'-started.json',['lane'=>$lane,'HTTP_budget'=>$final?4:26,'source_manifest_sha256'=>hash_file('sha256',__DIR__.($final?'/source-final-sha.json':'/source-frozen-sha.json'))]);$results=[];
try{
 foreach($cases as $scenario=>$case){$url=$base.$case['path'];$headers=['Host: '.$case['host'],'Platform: POC','Content-Type: application/json','X-Pilot-Scenario: '.$scenario];if($case['auth'])$headers[]='Access-Token: '.$tokens[$case['context']];$entry=['scenario'=>$scenario,'method'=>'POST','path'=>$case['path'],'started'=>true,'response_received'=>false,'body_sha256'=>hash('sha256',$case['body_raw'])];
  file_put_contents($runtime.($final?'/http-attempts-FINAL.jsonl':'/http-attempts.jsonl'),json_encode($entry)."\n",FILE_APPEND|LOCK_EX);chmod($runtime.($final?'/http-attempts-FINAL.jsonl':'/http-attempts.jsonl'),0600);
  $ctx=stream_context_create(['http'=>['method'=>'POST','header'=>implode("\r\n",$headers),'content'=>$case['body_raw'],'timeout'=>30,'ignore_errors'=>true]]);$started=microtime(true);$raw=file_get_contents($url,false,$ctx);$responseHeaders=$http_response_header??[];$entry['response_received']=$raw!==false;$entry['response_headers']=$responseHeaders;$entry['elapsed_ms']=(microtime(true)-$started)*1000;$entry['raw']=$raw;$persist('response-'.$scenario.'.json',$entry);
  if($raw!==false){file_put_contents($runtime.'/response-'.$scenario.'.body',$raw);chmod($runtime.'/response-'.$scenario.'.body',0600);}$body=$raw!==false?json_decode($raw,true):null;$results[]=['scenario'=>$scenario,'received'=>$raw!==false,'json'=>is_array($body),'status'=>$body['status']??null,'harness_error'=>$body['harness_error']??null,'raw_sha256'=>$raw!==false?hash('sha256',$raw):null];
 }
 $after=$own();$check($after===$fixture['after'],'Full42 batch end exactly unchanged');$enumAfter=$read('SELECT * FROM yoshop_config_enum WHERE enum_type IN (6,7,8,9,10,11) AND is_delete=0 ORDER BY enum_type,'.($dm?'"ORDER"':'`order`'));$check($enumAfter===$enumBefore,'All179 natural config dictionary rows unchanged including native sequence');
 $persist($final?'final-FINAL-original.json':'final-original.json',['lane'=>$lane,'original'=>$after,'enum_before'=>$enumBefore,'enum_after'=>$enumAfter,'retained13_exact'=>true]);
}finally{
 foreach($tokens as $token)$cache->delete($token);$out=['lane'=>$lane,'true_HTTP'=>count($results),'results'=>$results,'all_own_tokens_absent'=>count(array_filter($tokens,static function($t)use($cache){return $cache->has($t);}))===0];$persist('run-'.$phase.'.json',$out);file_put_contents(__DIR__.'/run-'.$phase.'-'.$lane.'.json',json_encode($out,JSON_PRETTY_PRINT));echo json_encode($out),"\n";
}
