<?php
require __DIR__.'/common.php';require __DIR__.'/observe.php';require __DIR__.'/Oracle.php';
if(is_file(__DIR__.'/private/attempts.json'))throw new RuntimeException('Attempts exist; no HTTP replay');$current=$source();$expected=json_decode(file_get_contents(__DIR__.'/private/lease-expected-'.$lane.'.json'),true)['source_after'];if($current!==$expected)throw new RuntimeException('Fresh full fetch lease');$auth=json_decode(file_get_contents(__DIR__.'/private/auth.json'),true);$uuid=$plan['target'][$lane]['uuid'];$attempts=[];$save('attempts.json',[]);
foreach($plan['cases']as $spec)foreach(['update','info']as $action){
 $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 row');$params=['uuid'=>$uuid];if($action==='update'){foreach($plan['SET_fields']as $f)if($f!=='is_own')$params[$f]=$f==='use_weight'?$spec['value']:$rows[0][$f];}
 $case=['label'=>$spec['label'].'-'.$action,'path'=>'/m/nutrition/'.$action,'params'=>$params,'spec'=>$spec];$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:'.$plan['ports'][$lane].$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);
 // Wait only for the already-sent request's observer file, never resend HTTP.
 $f=__DIR__.'/private/wire-'.$case['label'].'.json';for($wait=0;!is_file($f)&&$wait<200;$wait++)usleep(50000);if($body===false||!is_file($f))throw new RuntimeException('Original HTTP or observer missing; no replay');$w=json_decode(file_get_contents($f),true);$dto=json_decode($body,true);$preFile=__DIR__.'/private/response-'.$case['label'].'.json';$pre=is_file($preFile)?json_decode(file_get_contents($preFile),true):null;
 if(!$pre||$pre['body']!==$body||$w['body']!==$body||$w['status']!==200||isset($w['oracle_error'])||isset($w['business_or_send_error'])||!($w['protected_equal']??false))throw new RuntimeException('Original response/scope uncertain; no replay');$protected($current,$w['after'],$uuid);
 $dml=array_values(array_filter($w['native'],static function($e){return ($e['layer']??'')==='PDOStatement.execute'&&strpos($e['sql']??'','UPDATE ')===0;}));
 if($action==='info'){$oracle=nfInfoOracle($rows[0],$lane);if($dto!==$oracle||$w['DML_attempts']!==0||$current!==$w['after'])throw new RuntimeException('Full info DTO/lease oracle');$attempts[$i]['complete_info_oracle_equal']=true;}
 elseif($spec['target_DML_attempt_max']===0){if($dto!==$spec['expected_update_envelope']||$w['DML_attempts']!==0||$current!==$w['after'])throw new RuntimeException('Prefix rejection oracle');}
 else{
  if(count($dml)!==1||$w['DML_attempts']!==1)throw new RuntimeException('One native target attempt required');$e=$dml[0];
  if($e['success']){if($dto!==['code'=>0,'message'=>'编辑营养品成功','data'=>[]]||!in_array($e['rowCount'],[0,1],true))throw new RuntimeException('Native success envelope/affected scope');
   if($e['rowCount']===0){$metadata=json_decode(file_get_contents(__DIR__.'/private/scope-metadata.json'),true);if(!($metadata['target_no_trigger_or_auto_effect']??false)||$current!==$w['after'])throw new RuntimeException('Noop unknown effects or full-row drift');$v=$w['physical']['fields']['computed_weight']['value'];$want=$spec['value']==='3.5e38'?3.4028234663852886e38:($spec['value']==='12.347'?12.347000122070312:null);if($want===null||$v!==$want)throw new RuntimeException('Noop intended physical value not proven');$attempts[$i]['native_noop_full_row_and_intended_equal']=true;}
  }else{if(($dto['code']??null)!==1||($dto['data']??null)!==[]||!is_string($dto['message']??null)||$current!==$w['after']||!isset($e['error']['errorInfo']))throw new RuntimeException('Failure not proven bounded unchanged');$attempts[$i]['diagnosed_bounded_native_error']=$e['error'];}
 }
 $current=$w['after'];$attempts[$i]['verified']=true;$save('attempts.json',$attempts);$save('current-final-lease.json',['source'=>$current]);
}
$save('fetch-complete.json',['HTTP'=>count($attempts),'complete'=>true,'source'=>$current]);echo json_encode(['lane'=>$lane,'HTTP'=>count($attempts),'completed'=>true,'observer_SQL_from_fetch'=>count($GLOBALS['NF_ORACLE'])]),PHP_EOL;
