<?php
require __DIR__.'/recover.php';
function f27r_run($r,$p,$hashes){foreach($hashes as $k=>$v)f27_assert(getenv('F27R_ROOT_'.strtoupper($k))===$v,'Root recovery exact approval');f27_assert(hash_file('sha256',__DIR__.'/../runner.php')===$r['source_core_sha256']&&hash_file('sha256',__DIR__.'/../execute.php')===$r['source_execute_sha256']&&hash_file('sha256',__DIR__.'/../plan-B.json')===$r['source_plan_sha256'],'Preserved original tools bytes');$source=f27r_source($r,$p);$dir=$r['runtime'];f27_assert(!file_exists($dir)&&mkdir($dir,0700),'Exclusive once recovery runtime');$h=fopen($dir.'/events.jsonl','x');f27_assert(is_resource($h)&&chmod($dir.'/events.jsonl',0600),'Private append journal');$state=['cursor'=>0,'read'=>0,'DDL'=>0,'DML'=>0,'fresh_proven'=>false,'dropped'=>false];$meta=[];$identity=false;$snapshot=false;$stmt=null;
try{f27_append($h,['event'=>'start','hashes'=>$hashes,'original_cursor_retained'=>105,'original_completed_prefix'=>106,'source_raw_sha256'=>$r['source_raw_sha256'],'source_counts'=>$r['source_actual_counts']]);$db=f27_connect($p);foreach($r['steps']as $s){f27_assert($s===$r['steps'][$state['cursor']]&&$state[$s['kind']]<$r['budget'][$s['kind']],'Exact recovery SQL/type/order/budget no replay');if($s['kind']==='DDL')f27_assert($s['source_ordinal']===107&&$s['role']==='drop_table'&&$state['fresh_proven']&&!$state['dropped'],'Only original unsent exact own DROP after fresh full proof');f27_append($h,['event'=>'append-before','statement'=>$s,'state'=>$state]);$state[$s['kind']]++;$stmt=$db->prepare($s['SQL']);foreach($s['binds']as $i=>$v)f27_assert($stmt->bindValue($i+1,$v,$s['PDO_types'][$i]),'Exact binds');f27_assert($stmt->execute(),'Original native execute');if($s['kind']==='DDL'){f27_append($h,['event'=>'original-write-result','statement'=>$s,'rowCount'=>$stmt->rowCount(),'errorInfo'=>$stmt->errorInfo()]);$state['dropped']=true;}else{list($rows,$types,$keys,$streams,$bits)=f27_materialize($stmt->fetchAll(PDO::FETCH_ASSOC));f27_append($h,['event'=>'original-read-result','statement'=>$s,'rows'=>$rows,'native_types'=>$types,'native_keys'=>$keys,'native_streams'=>$streams,'native_float_bits'=>$bits,'errorInfo'=>$stmt->errorInfo()]);$role=$s['role'];$q=$s['read_query'];if($role==='fresh_identity'){f27_assert($rows===$source['identity'],'Original identity exact');$identity=true;}elseif($role==='fresh_snapshot'){f27_snapshot($rows,$types,$p);f27_assert(f27_native($rows,$types,$p)===f27_native($source['row']['rows'],$source['row']['native_types'],$p),'Original cleanup full27 bytes/types/LOB lease same');$snapshot=true;}elseif($role==='fresh_schema'){$meta[$q]=$rows;f27_assert($rows===$source['meta']['cleanup_schema'][$q],'Original cleanup exact current metadata '.$q);if($q==='ddl'){f27r_compare($source['meta']['created_schema'],$meta,$p);f27_assert($identity&&$snapshot&&count($meta)===9,'All11 fresh ownership checks complete');$state['fresh_proven']=true;}}elseif($role==='warnings')f27_assert($state['dropped']&&$rows===[],'Original same-PDO DROP warnings0');elseif($role==='zero')f27_assert($state['dropped']&&$rows===[],'Exact owned final closure0');else f27_assert(false,'Unknown recovery read role');}$state['cursor']++;}f27_assert($state['read']===19&&$state['DDL']===1&&$state['dropped'],'Completed tail only');f27_append($h,['event'=>'complete','state'=>$state,'cumulative_counts'=>['read'=>105,'DML'=>19,'DDL'=>2],'HTTP'=>0,'business_writes'=>0,'original_failure_preserved'=>true]);fclose($h);echo f27_json(['status'=>'B_TAIL_COMPLETE_ORIGINAL_FAILURE_PRESERVED','cumulative_counts'=>['read'=>105,'DML'=>19,'DDL'=>2]])."\n";return 0;
}catch(Throwable $e){f27_append($h,['event'=>'stopped_no_retry_no_cleanup','message'=>$e->getMessage(),'errorInfo'=>$stmt?$stmt->errorInfo():null,'state'=>$state]);fclose($h);fwrite(STDERR,f27_json(['status'=>'STOPPED','state'=>$state])."\n");return 1;}}
if(realpath($_SERVER['SCRIPT_FILENAME'])===__FILE__){try{$r=json_decode(file_get_contents(__DIR__.'/plan.json'),true);f27r_gate($r);$p=f27_reference()['B'];$hashes=['plan_sha'=>hash_file('sha256',__DIR__.'/plan.json'),'runner_sha'=>hash_file('sha256',__FILE__),'overlay_sha'=>hash_file('sha256',__DIR__.'/recover.php')];$mode=$argv[1]??'--gate';if($mode==='--gate'){echo f27_json(['status'=>'PURE_B_TAIL_GATE_GREEN','hashes'=>$hashes,'connections'=>0,'read'=>19,'DDL'=>1,'DML'=>0])."\n";exit(0);}f27_assert($mode==='--execute','Known mode');exit(f27r_run($r,$p,$hashes));}catch(Throwable $e){fwrite(STDERR,$e->getMessage()."\n");exit(1);}}
