<?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);$f=__DIR__.'/private/tool-failure-'.str_replace('.','-',uniqid('',true)).'.json';file_put_contents($f,json_encode($r,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));chmod($f,0600);echo json_encode(['tool_error_class'=>get_class($e),'reason_sha256'=>hash('sha256',$e->getMessage())]),"\n";exit(2);});
$lane=getenv('NR_LANE');$root=getenv('NR_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('Not code-local');if($cfg['charset']!=='utf8'||(string)($cfg['hostport']?:3306)!=='3306'||!empty($cfg['params']))throw new RuntimeException('Effective 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];
$db=new PDO($dsn,$cfg['username'],$cfg['password'],$options);
$q=static function(string $sql,array $binds=[])use($db):array{if(!preg_match('/^SELECT\b/',$sql)||preg_match('/\b(INTO|UPDATE|CALL|SLEEP|BENCHMARK)\b/i',$sql)||strpos($sql,';')!==false)throw new RuntimeException('Oracle SELECT gate');$s=$db->prepare($sql);foreach($binds 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);$rows[]=array_change_key_case($r,CASE_LOWER);if(count($rows)>150)throw new RuntimeException('Oracle row cap');}$GLOBALS['NR_ORACLE'][]=['queryString'=>$s->queryString,'binds'=>$binds,'rows'=>preg_match('/FROM ydy_config /',$sql)?null:$rows,'rows_count'=>count($rows),'rows_sha256'=>preg_match('/FROM ydy_config /',$sql)?hash('sha256',json_encode($rows,JSON_PRESERVE_ZERO_FRACTION)):null,'rowCount'=>$s->rowCount()];return $rows;};
$save=static function($name,$v){if(!is_dir(__DIR__.'/private'))mkdir(__DIR__.'/private',0700);chmod(__DIR__.'/private',0700);$j=json_encode($v,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT|JSON_PRESERVE_ZERO_FRACTION);if($j===false)throw new RuntimeException('Invalid UTF8 not normalized');file_put_contents(__DIR__.'/private/'.$name,$j);chmod(__DIR__.'/private/'.$name,0600);};
$productUuid=$lane==='B'?'B8247519-0EDA-6239-9A8A-FEA2D6C86F4B':'FCEECEFB-C32E-4977-8A65-EE2210A42095';
$source=static function()use($q,$lane,$productUuid){$r=[];$r['nutrition']=$q('SELECT * FROM ydy_nutrition WHERE id=? AND uuid=? AND name=?',[$lane==='B'?178:7,$productUuid,'CDXNF11F5-candidate-product']);if(count($r['nutrition'])!==1)throw new RuntimeException('Exact candidate single row');$p=$r['nutrition'][0];$r['nutrition_set']=$q('SELECT * FROM ydy_nutrition_set WHERE uuid=?',[$p['set_uuid']]);$r['nutrition_category']=$q('SELECT * FROM ydy_nutrition_category WHERE uuid=?',[$p['nutrition_category_uuid']]);$r['nutrition_time']=$q('SELECT * FROM ydy_nutrition_time WHERE uuid=?',[$p['use_time']]);$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%']);$clock=$q('SELECT config_key,config_value FROM ydy_config WHERE status=? AND config_key IN (?,?,?,?,?,?) ORDER BY id',[1,'morning_start','morning_end','noon_start','noon_end','night_start','night_end']);$r['config_lease']=['rows'=>count($clock),'sha256'=>hash('sha256',json_encode($clock,JSON_PRESERVE_ZERO_FRACTION))];$r['match_count']=$q('SELECT COUNT(*) AS n FROM ydy_nutrition WHERE is_del=? AND (name LIKE ? OR synopsis LIKE ?)',[1,'%CDXNF11F5-candidate-product%','%CDXNF11F5-candidate-product%']);$r['active_count']=$q('SELECT COUNT(*) AS n FROM ydy_nutrition WHERE is_del=?',[1]);$fields=['power','carbohydrate','protein','fat','sodium','use_weight'];$expr=[];foreach($fields as $f){$expr[]=$f;$expr[]=$lane==='B'?$f.'+0e0 AS '.$f.'_computed':'CAST('.$f.' AS DOUBLE) AS '.$f.'_computed';}$r['physical_native']=$q('SELECT '.implode(',',$expr).' FROM ydy_nutrition WHERE uuid=?',[$productUuid]);return $r;};
