<?php
require __DIR__.'/common.php';require __DIR__.'/observe.php';
if(is_file(__DIR__.'/private/attempts.json'))throw new RuntimeException('Attempts exist; no successful replay');
$expected=json_decode(file_get_contents(__DIR__.'/private/lease-expected-'.$lane.'.json'),true)['source_after'];$current=$source();if($current!==$expected)throw new RuntimeException('Fresh full lease mismatch');$auth=json_decode(file_get_contents(__DIR__.'/private/auth.json'),true);$port=$plan['ports'][$lane];$attempts=[];$save('attempts.json',[]);$uuid=$lane==='B'?'B8247519-0EDA-6239-9A8A-FEA2D6C86F4B':'FCEECEFB-C32E-4977-8A65-EE2210A42095';
foreach($plan['cases']as $spec){
 $rows=array_values(array_filter($current['nutrition'],static function($r)use($uuid){return $r['uuid']===$uuid;}));if(count($rows)!==1)throw new RuntimeException('Exact own current row');$params=['uuid'=>$uuid];
 if(isset($spec['value'])){foreach(['name','set_uuid','use_weight','use_number','use_weight_unit','use_number_unit','use_time','use_method','employ','is_nutrition_station','supplier','nutrition_category_uuid']as $f)$params[$f]=$rows[0][$f];$params['use_weight']=$spec['value'];}
 $case=['label'=>$spec['label'],'path'=>$spec['path'],'params'=>$params];$save('current-case.json',$case);$save('current-lease.json',$current);
 $payload=json_encode($params,JSON_UNESCAPED_UNICODE|JSON_PRESERVE_ZERO_FRACTION);$attempts[]=['case'=>$case,'payload_base64'=>base64_encode($payload),'started'=>true,'complete'=>false];$i=count($attempts)-1;$save('attempts.json',$attempts);
 $ctx=stream_context_create(['http'=>['method'=>'POST','header'=>"Content-Type: application/json\r\nToken: ".$auth['token']."\r\nX-CDX-Case: ".$case['label']."\r\n",'content'=>$payload,'ignore_errors'=>true,'follow_location'=>0,'timeout'=>30]]);$body=file_get_contents('http://127.0.0.1:'.$port.$case['path'],false,$ctx);$attempts[$i]['complete']=$body!==false;$attempts[$i]['headers']=$http_response_header??[];$attempts[$i]['body_base64']=$body===false?null:base64_encode($body);$save('attempts.json',$attempts);
 $wire=__DIR__.'/private/wire-'.$case['label'].'.json';if($body===false||!is_file($wire))throw new RuntimeException('Missing client/server evidence; no replay');$w=json_decode(file_get_contents($wire),true);$dto=json_decode($body,true);
 if($w['body']!==$body||$w['status']!==200||($dto['code']??null)!==0||!($w['protected_equal']??false)||isset($w['oracle_error']))throw new RuntimeException('Wire/DTO/lease red; no replay');
 foreach($w['native']as $e)if(isset($e['error']))throw new RuntimeException('Native gate/SQL error; no replay');
 if($w['DML_attempts']!==(isset($spec['value'])?1:0))throw new RuntimeException('DML budget exact');
 $protected($current,$w['after'],$uuid);$current=$w['after'];
}
$save('baseline-final.json',['source'=>$current,'oracle'=>$GLOBALS['NF_ORACLE'],'HTTP'=>count($attempts),'DML'=>2,'physical'=>$physical($uuid)]);echo json_encode(['lane'=>$lane,'HTTP'=>count($attempts),'DML'=>2,'completed'=>true]),"\n";

