<?php
declare(strict_types=1);
$runtimeParent='/tmp/cdx-nutrition-report24-20261011';
require $runtimeParent.'/common.php';
$save=static function($name,$v){if(!is_dir(__DIR__.'/private'))mkdir(__DIR__.'/private',0700);chmod(__DIR__.'/private',0700);$json=json_encode($v,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT|JSON_PRESERVE_ZERO_FRACTION);if($json===false)throw new RuntimeException('Bad UTF8');file_put_contents(__DIR__.'/private/'.$name,$json);chmod(__DIR__.'/private/'.$name,0600);};
set_exception_handler(static function(Throwable $e)use($save){$save('tool-failure.json',['class'=>get_class($e),'message'=>$e->getMessage(),'trace'=>$e->getTraceAsString()]);echo json_encode(['error_class'=>get_class($e),'reason_sha256'=>hash('sha256',$e->getMessage())]),"\n";exit(2);});
$approved='77c360f6eb2789b57b08ba22c047400f3be5ac0ff324ed9b9103ad8a63cca4cf';
if(hash_file('sha256',__DIR__.'/fixture-append2-plan.json')!==$approved||is_file(__DIR__.'/private/append-journal.json'))throw new RuntimeException('Unapproved plan or replay');
$add=json_decode(file_get_contents(__DIR__.'/fixture-append2-plan.json'),true);$lease=json_decode(file_get_contents(__DIR__.'/private/preflight-lease-'.$lane.'.json'),true);
$old=$source();$expected=json_decode(file_get_contents($runtimeParent.'/private/batch-after.json'),true);unset($expected['sentinel']);if($old!==$expected)throw new RuntimeException('Original6 own lease drift');
foreach(['foods_composition','dish']as $t){
 $meta=$lane==='B'?$q('SELECT COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? ORDER BY ORDINAL_POSITION',['ydy_'.$t]):$q('SELECT COLUMN_NAME,DATA_TYPE,DATA_LENGTH,DATA_PRECISION,DATA_SCALE,NULLABLE,DATA_DEFAULT FROM USER_TAB_COLUMNS WHERE TABLE_NAME=? ORDER BY COLUMN_ID',['YDY_'.strtoupper($t)]);
 if($meta!==$lease['schema'][$t])throw new RuntimeException('Schema/default drift');
 $triggers=$lane==='B'?$q('SELECT TRIGGER_NAME,ACTION_TIMING,EVENT_MANIPULATION,ACTION_STATEMENT FROM information_schema.TRIGGERS WHERE EVENT_OBJECT_SCHEMA=DATABASE() AND EVENT_OBJECT_TABLE=? ORDER BY TRIGGER_NAME',['ydy_'.$t]):$q('SELECT * FROM USER_TRIGGERS WHERE TABLE_NAME=? ORDER BY TRIGGER_NAME',['YDY_'.strtoupper($t)]);
 $cons=$lane==='B'?$q('SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE FROM information_schema.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? ORDER BY CONSTRAINT_NAME',['ydy_'.$t]):$q('SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,STATUS,SEARCH_CONDITION FROM USER_CONSTRAINTS WHERE TABLE_NAME=? ORDER BY CONSTRAINT_NAME',['YDY_'.strtoupper($t)]);
 if($triggers!==[]||$cons!==$lease['objects'][$t]['constraints'])throw new RuntimeException('Trigger/FK drift');
}
if($q('SELECT id FROM ydy_foods_composition WHERE name=? AND create_by=?',['CDXNR11A食材','CDXNR11A'])!==[]||$q('SELECT id FROM ydy_dish WHERE uuid=?',['C8EAA110-0005-4000-8000-202610110005'])!==[])throw new RuntimeException('Append marker collision');
$j=['lane'=>$lane,'approved_plan_sha256'=>$approved,'committed'=>false,'events'=>[]];$save('append-before.json',$old);$save('append-journal.json',$j);$db->beginTransaction();
try{foreach($add['rows']as $i=>$row){
 $binds=$row['pdo_binds'];if($i===1){if(!isset($foodId)||$foodId<1||$foodId>2147483647)throw new RuntimeException('Own identity');foreach($binds as &$b)if(is_array($b['value']))$b['value']=$foodId;unset($b);}
 $j['events'][]=['queryString'=>$row['sql'],'binds'=>$binds,'sent'=>true,'success'=>false];$save('append-journal.json',$j);$s=$db->prepare($row['sql']);foreach($binds as $k=>$b)$s->bindValue($k+1,$b['value'],$b['type']);$s->execute();
 $j['events'][$i]['success']=true;$j['events'][$i]['rowCount']=$s->rowCount();$j['events'][$i]['errorInfo']=$s->errorInfo();$save('append-journal.json',$j);if($s->rowCount()!==1)throw new RuntimeException('Append exact1');
 $raw=$i===0?$q('SELECT * FROM ydy_foods_composition WHERE name=? AND create_by=?',['CDXNR11A食材','CDXNR11A']):$q('SELECT * FROM ydy_dish WHERE uuid=?',['C8EAA110-0005-4000-8000-202610110005']);
 if(count($raw)!==1)throw new RuntimeException('Append exact owned1');
 if($i===0){$id=$raw[0]['id'];if(!is_numeric($id)||(string)(int)$id!==(string)$id||(int)$id<=0)throw new RuntimeException('Exact generated int');$foodId=(int)$id;}
 foreach(array_keys($row['values'])as $k=>$field){$v=$binds[$k]['value'];$got=$raw[0][$field];$ok=is_numeric($v)?is_numeric($got)&&(float)$v===(float)$got:$got===$v;if(in_array($field,['create_time','update_time'],true))$ok=$got===$v||$got===$v.'.000000';if(!$ok)throw new RuntimeException('Append readback '.$field);}
 $j['events'][$i]['original_row']=$raw[0];$save('append-journal.json',$j);
}$after=$source();if($after!==$old)throw new RuntimeException('Original6 changed');$db->commit();$j['committed']=true;$j['food_id']=$foodId;$save('append-journal.json',$j);$save('append-after.json',$after);$save('append-oracle.json',$GLOBALS['NR_ORACLE']);echo json_encode(['lane'=>$lane,'INSERT'=>2,'committed'=>true,'food_id'=>$foodId,'original6_exact'=>true]),"\n";
}catch(Throwable $e){if($db->inTransaction())$db->rollBack();$j['error']=['class'=>get_class($e),'message'=>$e->getMessage()];$save('append-journal.json',$j);throw $e;}
