<?php
declare(strict_types=1);
$group=(int)($argv[1]??0);if(!in_array($group,[1,2,3,4],true))exit(78);$lane=getenv('NR_LANE');$port=$lane==='B'?18891:18892;$r=json_decode(file_get_contents(__DIR__.'/private/request.json'),true);$f=__DIR__.'/private/http-attempts-group'.$group.'.json';if(is_file($f))throw new RuntimeException('No HTTP replay');$a=[];
if($group===2&&!is_file(__DIR__.'/private/http-attempts-group1.json'))throw new RuntimeException('Group1 first');
foreach($r['cases']as $c){if($c['group']!==$group)continue;$a[]=['label'=>$c['label'],'path'=>$c['path'],'sent'=>true,'complete'=>false];$i=count($a)-1;$save=static function()use(&$a,$f){file_put_contents($f,json_encode($a,JSON_PRETTY_PRINT));chmod($f,0600);};$save();$ctx=stream_context_create(['http'=>['method'=>'POST','header'=>"Content-Type: application/x-www-form-urlencoded\r\nToken: ".$r['token']."\r\nX-CDX-Case: ".$c['label']."\r\n",'content'=>http_build_query($c['params']),'ignore_errors'=>true,'follow_location'=>0,'timeout'=>30]]);$body=file_get_contents('http://127.0.0.1:'.$port.$c['path'],false,$ctx);$a[$i]['complete']=$body!==false;$a[$i]['headers']=$http_response_header??[];$a[$i]['body_base64']=$body===false?null:base64_encode($body);$save();if($body===false||!is_file(__DIR__.'/private/wire-'.$c['label'].'.json'))throw new RuntimeException('HTTP incomplete; no blind retry');}
echo json_encode(['lane'=>$lane,'group'=>$group,'HTTP'=>count($a),'complete'=>count(array_filter($a,static function($x){return $x['complete'];}))]),"\n";
