<?php
declare(strict_types=1);
require __DIR__.'/gate.php';
umask(0077);
$p=lr_load(__DIR__.'/plan.json');$sequence=lr_sequence($p);
$log=__DIR__.'/private-run-C.jsonl';$h=fopen($log,'xb');lr_assert($h!==false,'Never overwrite/replay raw');chmod($log,0600);
$serial=0;$attempts=0;$selects=0;$prepareOnly=0;$cases=0;$db=null;$cfg=null;$statement=null;
$emit=static function(string $event,array $data=[])use($h,&$serial):void{
    $bytes=json_encode(['seq'=>++$serial,'utc'=>gmdate('c'),'lane'=>'C','event'=>$event,'data'=>$data],JSON_UNESCAPED_UNICODE|JSON_PRESERVE_ZERO_FRACTION|JSON_THROW_ON_ERROR)."\n";
    lr_assert(fwrite($h,$bytes)===strlen($bytes)&&fflush($h),'Durable append');
};
$error=static function(Throwable $e):array{return ['class'=>get_class($e),'code'=>$e->getCode(),'message'=>$e->getMessage(),'errorInfo'=>$e instanceof PDOException?($e->errorInfo??null):null];};
$typed=static function($v):array{$out=['php_type'=>gettype($v),'value'=>$v];if(is_float($v))$out+=['float17g'=>sprintf('%.17g',$v),'native_double_hex'=>bin2hex(pack('d',$v)),'byte_order'=>bin2hex(pack('L',1))==='01000000'?'little':'big'];return $out;};
set_error_handler(static function($severity,$message,$file,$line){throw new ErrorException($message,0,$severity,$file,$line);});
try{
    lr_assert(getenv('LR_ROOT')==='/tmp/zhct-dm-poc-20260928.fcpiiN/store','Original C config root only');
    $cfg=(static function(string $file):array{return require $file;})(getenv('LR_ROOT').'/application/database.php');
    lr_assert($cfg['hostname']==='127.0.0.1'&&(string)$cfg['hostport']==='5237'&&$cfg['database']==='ZHCT_APP','Exact nonproduction endpoint');
    lr_assert(!isset($cfg['params'][1002]),'No initSQL');
    $options=[PDO::ATTR_CASE=>PDO::CASE_LOWER,PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_ORACLE_NULLS=>PDO::NULL_NATURAL,PDO::ATTR_STRINGIFY_FETCHES=>false,PDO::ATTR_EMULATE_PREPARES=>false];
    foreach(($cfg['params']??[])as $k=>$v)$options[$k]=$v;
    lr_assert(!isset($options[PDO::ATTR_PERSISTENT])||$options[PDO::ATTR_PERSISTENT]===false,'No persistent connection');
    $db=new PDO('dm:host=127.0.0.1;port=5237;schema=ZHCT_APP',$cfg['username'],$cfg['password'],$options);
    $cfg=null;unset($options);
    $emit('connection-confirmed',['php'=>PHP_VERSION,'int_size'=>PHP_INT_SIZE,'precision'=>ini_get('precision'),'serialize_precision'=>ini_get('serialize_precision'),'plan_sha256'=>LR_PLAN_SHA,'runner_sha256'=>hash_file('sha256',__FILE__),'gate_sha256'=>hash_file('sha256',__DIR__.'/gate.php'),'params_initSQL'=>false,'B_SQL'=>0,'DDL'=>0,'DML'=>0,'natural'=>0,'HTTP'=>0,'transaction_calls'=>0]);
    $attrs=[];
    foreach([PDO::ATTR_DRIVER_NAME,PDO::ATTR_CLIENT_VERSION,PDO::ATTR_SERVER_VERSION,PDO::ATTR_EMULATE_PREPARES,PDO::ATTR_STRINGIFY_FETCHES,PDO::ATTR_CASE,PDO::ATTR_ERRMODE,PDO::ATTR_PERSISTENT]as $attr){
        try{$attrs[$attr]=['supported'=>true,'value'=>$db->getAttribute($attr)];}catch(Throwable $e){$attrs[$attr]=['supported'=>false,'error'=>$error($e)];}
    }
    $emit('PDO-attributes',['attributes'=>$attrs]);lr_assert(($attrs[PDO::ATTR_PERSISTENT]['supported']??false)&&$attrs[PDO::ATTR_PERSISTENT]['value']===false,'Actual nonpersistent PDO');
    foreach($sequence as $index=>$step){
        lr_step_gate($p,$sequence,$index,$step,$attempts);$attempts++;
        $actual=[];foreach($step['parameters']as $b)$actual[]=['original'=>$b,'runtime'=>$typed($b['runtime_value']),'pdo_type_code'=>$b['pdo_type_code']];
        $emit($step['kind']==='prepare_only'?'prepare-only-start':'read-start',['attempt'=>$attempts,'role'=>$step['role'],'case_id'=>$step['case_id'],'sql'=>$step['sql'],'sql_sha256'=>hash('sha256',$step['sql']),'parameters'=>$actual]);
        try{
            $statement=$db->prepare($step['sql']);
            if($step['kind']==='prepare_only'){
                $prepareOnly++;$emit('prepare-only-success',['attempt'=>$attempts,'role'=>$step['role'],'sql'=>$step['sql'],'errorInfo'=>$statement->errorInfo()]);$statement->closeCursor();$statement=null;continue;
            }
            foreach($step['parameters']as $b)lr_assert($statement->bindValue($b['position'],$b['runtime_value'],$b['pdo_type_code']),'Original bindValue succeeded');
            $selects++;lr_assert($statement->execute(),'SELECT execute');$executeInfo=$statement->errorInfo();$rows=[];$types=[];
            $rowCap=$step['role']==='identity_version'?16:1;
            while(($row=$statement->fetch(PDO::FETCH_ASSOC))!==false){
                $row=array_change_key_case($row,CASE_LOWER);$rows[]=$row;$types[]=array_map($typed,$row);
                $emit('row-observed',['attempt'=>$attempts,'case_id'=>$step['case_id'],'row_number'=>count($rows),'row'=>$row,'typed_row'=>end($types)]);
                lr_assert(count($rows)<=$rowCap,'Row limit');
                lr_assert(strlen(json_encode(['rows'=>$rows,'typed_rows'=>$types],JSON_PRESERVE_ZERO_FRACTION|JSON_THROW_ON_ERROR))<=65536,'Row/typed64KB limit');
            }
            $columns=[];for($i=0;$i<$statement->columnCount();$i++){$m=$statement->getColumnMeta($i);lr_assert($m!==false,'Known column metadata');$columns[]=$m;}
            $meta=['requested'=>true,'supported'=>true,'columns'=>$columns];
            $observed=['attempt'=>$attempts,'role'=>$step['role'],'case_id'=>$step['case_id'],'sql'=>$step['sql'],'rows'=>$rows,'typed_rows'=>$types,'row_count'=>count($rows),'execute_errorInfo'=>$executeInfo,'fetch_errorInfo'=>$statement->errorInfo(),'column_metadata'=>$meta,'warning_status'=>'unknown'];
            $bytes=strlen(json_encode($observed,JSON_UNESCAPED_UNICODE|JSON_PRESERVE_ZERO_FRACTION|JSON_THROW_ON_ERROR));$observed['serialized_bytes_before_bytecount_field']=$bytes;
            $emit('read-observed-before-gate',$observed);
            lr_result_gate($step,$rows,$meta,$bytes);
            $statement->closeCursor();$statement=null;if($step['role']==='literal_rint')$cases++;
            $emit('read-success',['attempt'=>$attempts,'role'=>$step['role'],'case_id'=>$step['case_id'],'gate_passed'=>true,'cases_completed'=>$cases]);
        }catch(Throwable $e){
            $emit('read-or-prepare-failure',['attempt'=>$attempts,'role'=>$step['role'],'case_id'=>$step['case_id'],'sql'=>$step['sql'],'error'=>$error($e),'statement_errorInfo'=>$statement instanceof PDOStatement?$statement->errorInfo():null]);throw $e;
        }
    }
    lr_assert($attempts===50&&$selects===49&&$prepareOnly===1&&$cases===47,'Exact completed readonly sequence');
    $db=null;$emit('connection-released',['PDO_released'=>true]);
    $emit('complete',['status'=>'COMPLETE_READONLY_LITERAL_CANDIDATE_NOT_BUSINESS_FIX','attempts'=>$attempts,'SELECT_executions'=>$selects,'prepare_only'=>$prepareOnly,'literal_cases'=>$cases,'DDL'=>0,'DML'=>0,'natural'=>0,'B_SQL'=>0,'HTTP'=>0,'transaction_calls'=>0,'new_objects_created_by_runner'=>0,'prior_object0_source'=>'previous sealed two-round cleanup; no new catalog SQL authorized','warning_status'=>'unknown']);
    fclose($h);echo json_encode(['status'=>'COMPLETE','attempts'=>$attempts,'SELECTs'=>$selects,'cases'=>$cases,'raw_sha256'=>hash_file('sha256',$log)]),"\n";
}catch(Throwable $e){
    $cfg=null;if($statement instanceof PDOStatement){try{$statement->closeCursor();}catch(Throwable $ignored){}}$statement=null;$db=null;
    $emit('stopped',['error'=>$error($e),'attempts'=>$attempts,'SELECT_executions'=>$selects,'prepare_only'=>$prepareOnly,'literal_cases'=>$cases,'DDL'=>0,'DML'=>0,'natural'=>0,'B_SQL'=>0,'HTTP'=>0,'transaction_calls'=>0,'connection_released'=>true,'retry'=>false]);
    fclose($h);echo json_encode(['status'=>'STOPPED','attempts'=>$attempts,'SELECTs'=>$selects,'cases'=>$cases,'raw_sha256'=>hash_file('sha256',$log)]),"\n";exit(2);
}
