<?php
declare(strict_types=1);
set_exception_handler(static function(Throwable $e):void{$r=['class'=>get_class($e),'message'=>$e->getMessage(),'trace'=>$e->getTraceAsString()];if(!is_dir(__DIR__.'/private'))mkdir(__DIR__.'/private',0700);$file=__DIR__.'/private/tool-failure-'.str_replace('.','-',uniqid('',true)).'.json';file_put_contents($file,json_encode($r,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));chmod($file,0600);echo json_encode(['tool_error_class'=>get_class($e),'reason_sha256'=>hash('sha256',$e->getMessage())]),"\n";exit(2);});
$lane=getenv('FL_LANE');$root=getenv('FL_ROOT');
if(!in_array($lane,['B','C'],true))throw new RuntimeException('Lane');
defined('TP_ENV')||define('TP_ENV','local');defined('BUSINESS')||define('BUSINESS','');
defined('APP_PATH')||define('APP_PATH',$lane==='B'&&!is_dir(__DIR__.'/source/application')?'/workspace/zhct/zhctproject/store/application/':__DIR__.'/source/application/');defined('ROOT_PATH')||define('ROOT_PATH',$root.'/');
$cfg=(static function($f){return require $f;})($lane==='B'?'/workspace/zhct/zhctproject/store/application/database.php':$root.'/application/database.php');
if($lane==='B'){$local=(static function($f){return require $f;})('/workspace/zhct/zhctproject/store/application/config/local/database.php');foreach(['hostname','database','username','password']as $key)if($local[$key]!==$cfg[$key])throw new RuntimeException('Not code local');if($cfg['charset']!=='utf8'||(string)($cfg['hostport']?:3306)!=='3306'||!empty($cfg['params']))throw new RuntimeException('Effective config drift');}
else if($cfg['hostname']!=='127.0.0.1'||(string)$cfg['hostport']!=='5237'||$cfg['database']!=='ZHCT_APP')throw new RuntimeException('DM scope');
$dsn=$lane==='B'?'mysql:host='.$cfg['hostname'].';port='.($cfg['hostport']?:3306).';dbname='.$cfg['database'].';charset='.$cfg['charset']:'dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';
$options=[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_CASE=>PDO::CASE_LOWER,PDO::ATTR_ORACLE_NULLS=>PDO::NULL_NATURAL,PDO::ATTR_STRINGIFY_FETCHES=>false,PDO::ATTR_EMULATE_PREPARES=>false];
$db=new PDO($dsn,$cfg['username'],$cfg['password'],$options);
$q=static function(string $sql,array $params=[])use($db):array{if(!preg_match('/^SELECT\b/',$sql)||preg_match('/\b(INTO|UPDATE|CALL|SLEEP|BENCHMARK)\b/',$sql)||strpos($sql,';')!==false)throw new RuntimeException('Oracle SELECT gate');$s=$db->prepare($sql);foreach($params as $i=>$v)$s->bindValue($i+1,$v,is_int($v)?1:($v===null?0:2));$s->execute();$rows=[];while($r=$s->fetch(PDO::FETCH_ASSOC)){$r=array_change_key_case($r,CASE_LOWER);foreach($r as &$v)if(is_resource($v))$v=stream_get_contents($v);unset($v);$rows[]=$r;if(count($rows)>100)throw new RuntimeException('Oracle row cap');}$GLOBALS['FL_ORACLE'][]=['queryString'=>$s->queryString,'params'=>$params,'rows'=>$rows,'rowCount'=>$s->rowCount()];return $rows;};
$save=static function($name,$value){if(!is_dir(__DIR__.'/private'))mkdir(__DIR__.'/private',0700);$json=json_encode($value,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT|JSON_PRESERVE_ZERO_FRACTION);if($json===false)throw new RuntimeException('Invalid UTF8 cannot normalize');file_put_contents(__DIR__.'/private/'.$name,$json);chmod(__DIR__.'/private/'.$name,0600);};
$plan=json_decode(file_get_contents(__DIR__.'/fixture-plan.json'),true);$fixture=$plan['lanes'][$lane];
$source=static function(bool $batch=false)use($q,$fixture,$lane):array{
    $r=['supplement'=>$q('SELECT * FROM ydy_meal_order_supplement WHERE supplement_no=?',[$fixture['supplement_no']]),'order'=>$q('SELECT id,order_no,user_id,restaurant_id,refund_status,refund_amount,cash_refund_amount,subsidy_refund_amount,gift_refund_amount,is_delete FROM ydy_meal_order WHERE id=?',[$fixture['meal_order_id']]),'user'=>$q('SELECT id,uuid,account,name,staff_uuid,ai_user_id,balance,pay_money,type,status,is_delete FROM ydy_user WHERE id=? AND account LIKE ?',[$fixture['user_id'],'CDXPAY%']),'restaurant'=>$q('SELECT id,uuid,name,status,is_delete FROM ydy_restaurants WHERE id=?',[1]),'operator'=>$q('SELECT id,uuid,account,name,staff_uuid,type,status,is_delete FROM ydy_user WHERE id=? AND account LIKE ?',[$lane==='B'?97260:2791,'CDX%']),'equipment'=>$q('SELECT id,code,name,restaurant_id FROM ydy_equipment WHERE code=? AND restaurant_id=?',[$fixture['equipment_code'],1])];
    if($batch){foreach(['meal_order_supplement','meal_order','user','staff','staff_department','restaurants','equipment','security_audit_log','export_log','config']as $table)$r['aggregate'][$table]=$q('SELECT COUNT(*) AS n,MIN(id) AS min_id,MAX(id) AS max_id,SUM(id) AS sum_id FROM ydy_'.$table);}
    return $r;
};
