<?php
declare(strict_types=1);
require __DIR__.'/ScopeMarker.php';
$plan=json_decode(file_get_contents(__DIR__.'/execution-plan.json'),true);if(!is_array($plan))throw new RuntimeException('Plan object required');$marker=nfScopeMarker($plan);
$lane=getenv('NF_LANE');$root=getenv('NF_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',__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 $k)if($cfg[$k]!==$local[$k])throw new RuntimeException('Source local config');if($cfg['charset']!=='utf8'||(string)($cfg['hostport']?:3306)!=='3306'||!empty($cfg['params']))throw new RuntimeException('Source config drift');}
elseif($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=3306;dbname='.$cfg['database'].';charset=utf8':'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];
require_once __DIR__.'/Budget.php';
$db=new PDO($dsn,$cfg['username'],$cfg['password'],$options);$GLOBALS['NF_ORACLE']=[];
$q=static function($sql,$args=[])use($db){if(!preg_match('/^SELECT\b/',$sql)||strpos($sql,';')!==false)throw new RuntimeException('Read only oracle');NFObserverBudget::take();$GLOBALS["NF_ORACLE_ATTEMPTS"][]=["sql"=>$sql,"binds"=>$args,"started"=>true];$s=$db->prepare($sql);foreach($args 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)){foreach($r as &$v)if(is_resource($v))$v=stream_get_contents($v);unset($v);$r=array_change_key_case($r,CASE_LOWER);$rows[]=$r;if(count($rows)>100)throw new RuntimeException('Oracle cap');}$GLOBALS['NF_ORACLE'][]=['sql'=>$s->queryString,'binds'=>$args,'rows'=>$rows,'rowCount'=>$s->rowCount()];return $rows;};
$save=static function($name,$v){if(!is_dir(__DIR__.'/private'))mkdir(__DIR__.'/private',0700);$j=json_encode($v,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT|JSON_PRESERVE_ZERO_FRACTION);if($j===false)throw new RuntimeException('Non-JSON finite evidence');$f=__DIR__.'/private/'.$name;file_put_contents($f,$j);chmod($f,0600);};
// Plan and exact marker were validated before PDO.
$source=static function()use($q,$lane,$plan,$marker){$r=[];foreach(['nutrition','nutrition_template','nutrition_set','nutrition_category','nutrition_time']as $t)$r[$t]=$q('SELECT * FROM ydy_'.$t.' WHERE name LIKE ? ORDER BY id',[$marker.'%']);$templates=array_column($r['nutrition_template'],'uuid');$r['nutrition_template_ext']=$templates?$q('SELECT * FROM ydy_nutrition_template_ext WHERE template_uuid IN ('.implode(',',array_fill(0,count($templates),'?')).') ORDER BY id',$templates):[];$r['actor']=$q('SELECT id,uuid,account,name,type,status,is_delete,user_type,staff_uuid FROM ydy_user WHERE id=? AND account LIKE ?',[$lane==='B'?97260:2791,'CDX%']);$r['config']=$q('SELECT id,config_key,config_value,status FROM ydy_config WHERE config_key IN (?,?,?,?,?,?) ORDER BY id',['morning_start','morning_end','noon_start','noon_end','night_start','night_end']);$r['identity']=$q('SELECT id,identity_type,is_delete FROM ydy_identity_type ORDER BY id');foreach(['nutrition','nutrition_template']as $t){$rows=$r[$t];$r[$t.'_native']=[];foreach($rows as $row){$fields=['power','carbohydrate','protein','fat','sodium'];$expr=[];foreach($fields as $f){$expr[]=$f;$expr[]=$lane==='B'?$f.'+0e0 AS '.$f.'_computed':'CAST('.$f.' AS DOUBLE) AS '.$f.'_computed';}$n=$q('SELECT '.implode(',',$expr).' FROM ydy_'.$t.' WHERE uuid=?',[$row['uuid']]);$bits=[];foreach($n[0]??[]as $f=>$v)$bits[$f]=['type'=>gettype($v),'bits64'=>is_float($v)?bin2hex(pack('d',$v)):null,'value'=>$v];$r[$t.'_native'][]=['uuid'=>$row['uuid'],'fields'=>$bits];}}return $r;};
