<?php
declare(strict_types=1);require __DIR__.'/WeightContract.php';
final class CoreGate extends WeightContract{
public static $storeCommitted=false;
public static function writer(){return false;}
public static function kind($db,$sql){$plain=preg_replace("/'(?:''|\\\\.|[^'\\\\])*'/s",'?', $sql);ck(!preg_match('/;|--|\/\*|\*\/|#|\b(?:DELETE|REPLACE|MERGE|CREATE|ALTER|DROP|TRUNCATE|GRANT|REVOKE|OUTFILE|DUMPFILE|LOAD|EXEC|EXECUTE|SLEEP|BENCHMARK|UTL_HTTP|NEXTVAL)\b/i',$plain),'No DELETE/DDL/unknown SQL');if($sql===self::COLUMNS||$sql===self::PRIMARY)return 'metadata_SELECT';if(preg_match('/^SHOW FULL COLUMNS FROM `([A-Za-z_][A-Za-z0-9_]*)`$/D',$sql,$m)){self::known($db,$m[1]);return 'metadata_SHOW';}if($sql==='CALL SP_TABLEDEF(?, ?)'&&self::$meta)return 'metadata_CALL';if(in_array($sql,["SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') schema_name FROM DUAL",'SELECT DATABASE() schema_name,VERSION() version'],true)){ck(self::$scenario==='CONSTRUCTOR_WARM','App live identity only beforeHTTP');return 'identity_SELECT';}ck(!preg_match('/\bUSER_(?:TAB_COLUMNS|CONSTRAINTS|CONS_COLUMNS|TABLES)\b/i',$sql),'Original metadata shapes only');if(preg_match('/^\s*SELECT\b/i',$sql)){ck(!preg_match('/\bINTO\b/i',$plain),'No SELECT INTO');if(preg_match('/\bFOR\s+UPDATE\s*$/i',$sql))ck($db==='AI'&&self::writer()&&preg_match('/\byoshop_user\b/i',$sql),'Only original own AI owner lock');preg_match_all('/\b(yoshop|ydy)_([a-z0-9_]+)/i',$sql,$m,PREG_SET_ORDER);ck(count($m)>0,'Scoped data SELECT');$allowed=$db==='AI'?['user','staff','user_weight','user_weight_status','user_score','user_score_log','user_bind','user_health_metric_record','user_oauth','store','store_setting','upload_file']:['user','measurement_session','measurement_session_raw','health_record'];foreach($m as $r)ck(($db==='AI'?strtolower($r[1])==='yoshop':strtolower($r[1])==='ydy')&&in_array(strtolower($r[2]),$allowed,true),'Only approved original data table');return 'SELECT';}if(preg_match('/^(INSERT INTO|UPDATE)\s+[`"]?((?:yoshop|ydy)_[a-z_]+)[`"]?/i',$sql,$m)){ck(self::writer(),'Only exact two scale writers');return strtoupper($m[1])==='UPDATE'?'UPDATE':'INSERT';}throw new RuntimeException('Unknown original SQL');}
public static function sessions(){global $runtime;$ids=[];foreach(['scale-flow.json','scale-flow-after-W2.json'] as $f)if(file_exists($runtime.'/'.$f))$ids=array_merge($ids,json_decode(file_get_contents($runtime.'/'.$f),true)['session_ids']);if(isset(self::$generated['ydy_measurement_session']))$ids[]=self::$generated['ydy_measurement_session'];return array_values(array_unique(array_map('strval',$ids)));}
public static function plan($db,$sql,$bind){global $runtime;$kind=self::kind($db,$sql);if(strpos($kind,'metadata_')===0){parent::plan($db,$sql,$bind);return;}if($kind==='identity_SELECT'){ck($bind===[],'Live App identity no binds');return;}$a=self::a();$vals=array_values(array_map(static function($x){return is_array($x)?$x[0]:$x;},$bind));$flat=array_map('strval',$vals);if($kind==='SELECT'){if(preg_match('/\b(?:yoshop_(?:user|staff|user_weight|user_weight_status|user_score|user_score_log|user_bind|user_health_metric_record|user_oauth)|ydy_user|ydy_measurement_session)\b/i',$sql))ck(in_array((string)$a['user_id'],$flat,true),'Only exact own actor data');if(preg_match('/\bydy_(?:measurement_session_raw|health_record)\b/i',$sql))ck(count(array_intersect($flat,self::sessions()))>0,'Only genuine owned session relation');if(preg_match('/\byoshop_store(?:_setting)?\b/i',$sql))ck(in_array('10001',$flat,true),'Only exact tenant config');if(stripos($sql,'yoshop_upload_file')!==false){$lease=json_decode(file_get_contents($runtime.'/tenant-file-lease.json'),true);$clean=str_replace(['`','"'],'',$sql);ck(preg_match('/file_id\s*=\s*:(\w+)/i',$clean,$m)&&isset($bind[$m[1]]),'Exact file equality');$v=$bind[$m[1]];ck(in_array((string)(is_array($v)?$v[0]:$v),$lease['allowed_file_ids'],true)&&in_array('10001',$flat,true),'Exact current tenant related file');}return;}
[$table,$v,$where,$pairs]=self::parse($sql,$bind);$w1=self::$scenario==='W1_WELLAND_ADD';$weight=$w1?'72.75':'73.34';$bmi=$w1?22.14:22.32;$vendor=$w1?'welland':'yunkangbao';if($db==='AI'){ck($kind==='UPDATE'&&self::$storeCommitted&&in_array($table,['yoshop_staff','yoshop_user_weight'],true),'Only AI own2U after real Store commit');self::types($table,$pairs,$bind);$keys=array_keys($where);sort($keys);$pk=$table==='yoshop_staff'?$a['staff_id']:json_decode(file_get_contents($runtime.'/scale-baseline.json'),true)['user_weight'][0]['id'];ck(in_array($keys,[['id'],['id','store_id']],true)&&(string)$where['id']===(string)$pk&&(!isset($where['store_id'])||$where['store_id']===10001),'Exact original indexed own UPDATE');ck(empty(self::$counts['UPDATE.'.$table]),'Each AI table once per writer');$want=$table==='yoshop_staff'?['weight'=>['php'=>'string','value'=>$weight],'update_time'=>'@clock']:['weight'=>['php'=>'string','value'=>$weight],'height'=>['php'=>'double','value'=>181.25],'bmi'=>['php'=>'double','value'=>$bmi],'update_time'=>'@clock'];self::equal($v,$want,$table);}
else{ck($kind==='INSERT'&&$where===[]&&in_array($table,['ydy_measurement_session','ydy_measurement_session_raw','ydy_health_record'],true),'Only scoped Store3table INSERT');$limit=$table==='ydy_health_record'?3:1;ck((self::$counts['INSERT.'.$table]??0)<$limit,'Exact Store INSERT cap');$schema=json_decode(file_get_contents($runtime.'/store-schema.json'),true)[substr($table,4)]['columns'];$types=[];foreach($schema as $c)$types[strtolower($c['column_name'])]=strtolower($c['data_type']);foreach($pairs as [$f,$p]){ck(isset($types[$f]),'Actual Store metadata field');if(strtoupper($p)==='NULL'){ck($v[$f]===null,'Original explicit NULL');continue;}$b=$bind[substr($p,1)];$type=preg_match('/int|bool|bit/',$types[$f])?1:(preg_match('/decimal|numeric|number|float|double|real/',$types[$f])?21:2);ck($b[1]===$type,'Original Store PDO metadata type');}$payload=json_decode(file_get_contents(__DIR__.'/execution-plan.json'),true)['cases'][$w1?0:2];$raw=json_encode(json_decode($payload['body_raw'],true)['form'],JSON_UNESCAPED_UNICODE);$measured=$w1?'@now':'2026-10-11 08:30:00';$sid=self::$generated['ydy_measurement_session']??null;
if($table==='ydy_measurement_session')$want=['ai_user_id'=>$a['user_id'],'event_type'=>'measurement','start_time'=>$measured,'end_time'=>$measured,'source_platform'=>'direct_device','vendor'=>$vendor,'device_type'=>'body_scale','device_model'=>$w1?'CDXSCALE11_WL':'CDXSCALE11_QN','raw_hash'=>null,'business_context'=>'health','is_valid'=>1,'created_at'=>'@now'];
elseif($table==='ydy_measurement_session_raw'){ck(is_int($sid)&&$sid>0,'Real generated session before raw');$want=['session_id'=>$sid,'data'=>$raw,'created_at'=>'@now'];}
else{ck(is_int($sid)&&$sid>0,'Real generated session before metric');$code=$v['metric_code']??'';$i=self::$counts['INSERT.ydy_health_record']??0;ck($code===['weight','height','bmi'][$i],'Original metric loop order');$values=['weight'=>(float)$weight,'height'=>181.25,'bmi'=>$bmi];$units=['weight'=>'kg','height'=>'cm','bmi'=>null];$want=['session_id'=>$sid,'ai_user_id'=>$a['user_id'],'metric_code'=>$code,'value'=>$values[$code],'unit'=>$units[$code],'segment'=>null,'segment_key'=>'','data_source_type'=>'algorithm','algorithm_vendor'=>$vendor,'algorithm_version'=>'CDXSCALE11S1','source_platform'=>$w1?'direct_device':'vendor_api','start_time'=>$measured,'end_time'=>$measured,'created_at'=>'@now'];}
$x=array_keys($v);$y=array_keys($want);sort($x);sort($y);ck($x===$y,'Exact Store source field-set');foreach($want as $f=>$value){if($value==='@now')ck(is_string($v[$f])&&preg_match('/^2026-10-11 \d\d:\d\d:\d\d$/D',$v[$f])&&strtotime($v[$f])>=self::$started-2&&strtotime($v[$f])<=time()+2,'Original source current seconds clock');else ck($v[$f]===$value,'Exact Store source PHP type/value '.$f);}}
self::$last[$db]=$table;
}}
