<?php
declare(strict_types=1);
date_default_timezone_set('Asia/Shanghai');$lane=(string)getenv('CATEGORY_LANE');$runtime=(string)getenv('CATEGORY_RUNTIME');$base=(string)getenv('CATEGORY_BASE');$dm=getenv('POC_DIALECT')==='dm';
$check=static function(bool $ok,string $why):void{if(!$ok)throw new RuntimeException($why);};$check(in_array($lane,['B','C'],true)&&preg_match('#^http://127\.0\.0\.1:1832[12]$#D',$base)===1,'Private weight lane');
$tenant=2147000921;$marker='CDXWT10C9D3';$tables=['user','staff','staff_weight','habit','user_weight_status','nurtition_target','meal_recommend','meal_recommend_history'];
$connect=static function()use($dm):PDO{try{return new PDO($dm?'dm:host=127.0.0.1;port=5238;schema=AIZHCT_APP':'mysql:host='.getenv('POC_AI_HOST').';port='.getenv('POC_AI_PORT').';dbname='.getenv('POC_AI_SCHEMA').';charset=utf8',getenv('POC_AI_USER'),getenv('POC_AI_PASSWORD'),[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_CASE=>PDO::CASE_LOWER]);}catch(Throwable $e){throw new RuntimeException('Weight database connection failed');}};
$db=$connect();if($dm)$check($db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn()==='AIZHCT_APP','DM identity');else $check(strpos((string)$db->query('SELECT VERSION()')->fetchColumn(),'5.6.')===0&&$db->query('SELECT DATABASE()')->fetchColumn()===getenv('POC_AI_SCHEMA'),'Code local MySQL identity');
$query=static function(string $sql,array $args=[])use($db):array{$s=$db->prepare($sql);$s->execute($args);$rows=$s->fetchAll(PDO::FETCH_ASSOC);foreach($rows as &$r)foreach($r as &$v)if(is_resource($v))$v=stream_get_contents($v);unset($r,$v);return $rows;};
$gate=json_decode((string)file_get_contents(__DIR__.'/structure-'.$lane.'.json'),true);$check(($gate['lane']??'')===$lane&&($gate['business_dml']??null)===0&&($gate['foreign_keys']??null)===0&&($gate['triggers']??null)===0,'Eight-table live metadata');
$names=array_map('strtolower',array_column($gate['metadata']['staff_weight']['columns'],'column_name'));$expected=['id','staff_id','height','weight','body_fat_rate','weight_status','bmi','energy_value','set_date','store_id','is_delete','create_by','create_time','update_time'];sort($names);sort($expected);$check($names===$expected,'Weight exact schema (all name missing known)');
$counts=static function()use($query,$tables,$tenant):array{$out=[];foreach($tables as $table)$out[$table]=(int)$query('SELECT COUNT(*) n FROM yoshop_'.$table.' WHERE store_id=?',[$tenant])[0]['n'];return $out;};
$ownedIds=[];$scanMetrics=[];
$snapshot=static function()use($connect,$dm,&$ownedIds,&$scanMetrics):array{
    $scan=$connect();if(!$dm)$scan->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,false);$out=[];$metrics=[];
    foreach(['user'=>'user_id','staff'=>'id','staff_weight'=>'id','habit'=>'id','user_weight_status'=>'id','nurtition_target'=>'id','general_vm'=>'id'] as $table=>$pk){$start=microtime(true);$s=$scan->query('SELECT * FROM yoshop_'.$table.' ORDER BY '.$pk);$hash=hash_init('sha256');$n=0;$excluded=0;
        while($row=$s->fetch(PDO::FETCH_ASSOC)){if(in_array((int)$row[$pk],$ownedIds[$table]??[],true)){$excluded++;continue;}foreach($row as &$v)if(is_resource($v))$v=stream_get_contents($v);unset($v);hash_update($hash,serialize($row));$n++;}$s->closeCursor();$out[$table]=['natural_rows'=>$n,'sha256'=>hash_final($hash)];$metrics[$table]=['natural_rows'=>$n,'excluded_exact_owned_pks'=>$excluded,'elapsed_ms'=>(int)round((microtime(true)-$start)*1000)];}
    $scanMetrics[]=$metrics;return $out;
};
