<?php
declare(strict_types=1);
$lane=getenv('FL_LANE');$port=$lane==='B'?18871:18872;$r=json_decode(file_get_contents(__DIR__.'/private/request.json'),true);
$phase=$argv[1]??'original';if(!in_array($phase,['original','retest','final'],true)||($phase==='retest'&&$lane!=='B'))throw new RuntimeException('Exact phase');$file=__DIR__.'/private/http-attempts'.($phase!=='original'?'-'.$phase:'').'.json';
if(is_file($file))throw new RuntimeException('No HTTP replay');$attempts=[];
foreach($r['cases']as $case){if($phase==='retest'&&!in_array($case['label'],['list-positive','list-page2','list-status40','detail-positive'],true))continue;if($phase==='final'&&!in_array($case['label'],['list-positive','detail-positive'],true))continue;$attempts[]=['label'=>$case['label'],'path'=>$case['path'],'sent'=>true,'complete'=>false];$i=count($attempts)-1;$persist=static function()use(&$attempts,$file){file_put_contents($file,json_encode($attempts,JSON_PRETTY_PRINT));chmod($file,0600);};$persist();
    $context=stream_context_create(['http'=>['method'=>'POST','header'=>"Content-Type: application/x-www-form-urlencoded\r\nToken: ".$r['token']."\r\nX-CDX-Case: ".$case['label']."\r\nX-CDX-Phase: ".$phase."\r\n",'content'=>http_build_query($case['params']),'ignore_errors'=>true,'follow_location'=>0,'timeout'=>20]]);
    $body=file_get_contents('http://127.0.0.1:'.$port.$case['path'],false,$context);$headers=$http_response_header??[];$attempts[$i]['complete']=$body!==false;$attempts[$i]['headers']=$headers;$attempts[$i]['body_base64']=$body===false?null:base64_encode($body);$attempts[$i]['body_sha256']=$body===false?null:hash('sha256',$body);$persist();
    if($body===false)throw new RuntimeException('HTTP incomplete: do not retry blindly');
    $wireFile=__DIR__.'/private/wire-'.$case['label'].($phase!=='original'?'-'.$phase:'').'.json';if(!is_file($wireFile))throw new RuntimeException('Missing native wire record');$wire=json_decode(file_get_contents($wireFile),true);if($case['kind']==='unreachable'&&$wire['native']!==[])throw new RuntimeException('Alias unexpected native SQL');
}
echo json_encode(['lane'=>$lane,'http_attempts'=>count($attempts),'complete'=>count(array_filter($attempts,static function($r){return $r['complete'];}))]),"\n";
