<?php
declare(strict_types=1);
// Standalone, SELECT-only; never boots business controllers or requires local override alone.
$lane=$argv[1]??''; if(!in_array($lane,['B','C'],true))exit(78);
$phase=$argv[2]??'initial';if(!in_array($phase,['initial','lease'],true))exit(78);
define('BUSINESS',''); define('TP_ENV','local');
define('APP_PATH',$lane==='B'?'/workspace/zhct/zhctproject/store/application/':'/tmp/zhct-dm-poc-20260928.fcpiiN/store/application/');
$cfg=(static function($f){return require $f;})(APP_PATH.'database.php');
if($lane==='B'){
 $local=(static function($f){return require $f;})(APP_PATH.'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';
$db=new PDO($dsn,$cfg['username'],$cfg['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_CASE=>PDO::CASE_LOWER,PDO::ATTR_STRINGIFY_FETCHES=>false,PDO::ATTR_EMULATE_PREPARES=>false]);
$out=['lane'=>$lane,'HTTP'=>0,'DML'=>0,'DDL'=>0,'connections'=>1,'events'=>[],'schema'=>[],'marked'=>[],'errors'=>[]];
$q=static function($sql,$binds=[])use($db,&$out){
 if(!preg_match('/^SELECT\b/',$sql)||preg_match('/\b(INTO|UPDATE|CALL|SLEEP|BENCHMARK)\b/i',$sql)||strpos($sql,';')!==false)throw new RuntimeException('SELECT gate');
 $ev=['queryString'=>$sql,'binds'=>$binds,'success'=>false];
 try{$s=$db->prepare($sql);foreach($binds as $i=>$v)$s->bindValue($i+1,$v,is_int($v)?PDO::PARAM_INT:PDO::PARAM_STR);$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('row cap');}
 $ev['success']=true;$ev['rowCount']=$s->rowCount();$ev['rows']=count($rows);$out['events'][]=$ev;return $rows;
 }catch(Throwable $e){$ev['error']=$e->getMessage();$out['events'][]=$ev;throw $e;}
};
$out['identity']=$lane==='B'?$q('SELECT VERSION() AS version,DATABASE() AS db,@@character_set_connection AS charset'):$q("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') AS db FROM DUAL");
if($lane==='B'&&strpos($out['identity'][0]['version'],'5.6.')!==0)throw new RuntimeException('MySQL version');
if($lane==='C'&&$out['identity'][0]['db']!=='ZHCT_APP')throw new RuntimeException('Schema identity');
foreach(($phase==='lease'?['staff','dishes','menu_recommend','date_menu','user','foods_composition']:['staff','department','staff_department','menu_recommend','menu_recommend_record','date_menu','dishes','dish','food','sport','initial_menu_log','menu_recommend_set'])as $t){
 try{$out['schema'][$t]=$lane==='B'?$q('SELECT COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? ORDER BY ORDINAL_POSITION',['ydy_'.$t]):$q('SELECT COLUMN_NAME,DATA_TYPE,DATA_LENGTH,DATA_PRECISION,DATA_SCALE,NULLABLE,DATA_DEFAULT FROM USER_TAB_COLUMNS WHERE TABLE_NAME=? ORDER BY COLUMN_ID',['YDY_'.strtoupper($t)]);}catch(Throwable $e){$out['errors'][]=['table'=>$t,'error'=>$e->getMessage()];}
}
if($phase==='lease'){
 foreach(['staff','dishes','menu_recommend','date_menu']as $t){$table='ydy_'.$t;
  $out['objects'][$t]['constraints']=$lane==='B'?$q('SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE FROM information_schema.TABLE_CONSTRAINTS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? ORDER BY CONSTRAINT_NAME',[$table]):$q('SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,STATUS,SEARCH_CONDITION FROM USER_CONSTRAINTS WHERE TABLE_NAME=? ORDER BY CONSTRAINT_NAME',[strtoupper($table)]);
  $out['objects'][$t]['indexes']=$lane==='B'?$q('SELECT INDEX_NAME,NON_UNIQUE,SEQ_IN_INDEX,COLUMN_NAME FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? ORDER BY INDEX_NAME,SEQ_IN_INDEX',[$table]):$q('SELECT INDEX_NAME,UNIQUENESS,INDEX_TYPE FROM USER_INDEXES WHERE TABLE_NAME=? ORDER BY INDEX_NAME',[strtoupper($table)]);
  $out['objects'][$t]['triggers']=$lane==='B'?$q('SELECT TRIGGER_NAME,ACTION_TIMING,EVENT_MANIPULATION,ACTION_STATEMENT FROM information_schema.TRIGGERS WHERE EVENT_OBJECT_SCHEMA=DATABASE() AND EVENT_OBJECT_TABLE=? ORDER BY TRIGGER_NAME',[$table]):$q('SELECT * FROM USER_TRIGGERS WHERE TABLE_NAME=? ORDER BY TRIGGER_NAME',[strtoupper($table)]);
  $out['collisions'][$t]=$q('SELECT id,uuid FROM '.$table.' WHERE uuid LIKE ?',['C8EAA110%']);
 }
 $out['operator']=$q('SELECT id,uuid,account,name,type,status,is_delete,user_type FROM ydy_user WHERE id=? AND account LIKE ?',[$lane==='B'?97260:2791,'CDX%']);
}else try{
 $out['marked']['staff']=$q('SELECT id,uuid,name,sex,birthday,height,weight,grade,status FROM ydy_staff WHERE name LIKE ? OR uuid LIKE ? ORDER BY id',['CDX%','CDX%']);
 $out['marked']['department']=$q('SELECT id,uuid,name,puuid,status,is_show FROM ydy_department WHERE name LIKE ? OR uuid LIKE ? ORDER BY id',['CDX%','CDX%']);
 foreach($out['marked']['staff']as $s){$u=$s['uuid'];
  $out['marked']['links'][$u]=$q('SELECT id,staff_uuid,department_uuid FROM ydy_staff_department WHERE staff_uuid=? ORDER BY id',[$u]);
  $out['marked']['recommend'][$u]=$q('SELECT id,uuid,staff_uuid,menu_date,total_power,prescription_power,carbohydrate_weight,protein_weight,fat_weight FROM ydy_menu_recommend WHERE staff_uuid=? ORDER BY id',[$u]);
  $out['marked']['menu'][$u]=$q('SELECT id,uuid,staff_uuid,menu_date,recommend_uuid,dishes_uuid,meal_times,meal_type,number FROM ydy_date_menu WHERE staff_uuid=? ORDER BY id',[$u]);
 }
}catch(Throwable $e){$out['errors'][]=['marked_read'=>$e->getMessage()];}
if(!is_dir(__DIR__.'/private'))mkdir(__DIR__.'/private',0700);chmod(__DIR__.'/private',0700);
$f=__DIR__.'/private/preflight-'.($phase==='initial'?'':$phase.'-').$lane.'.json';file_put_contents($f,json_encode($out,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT|JSON_PRESERVE_ZERO_FRACTION));chmod($f,0600);
echo json_encode(['lane'=>$lane,'HTTP'=>0,'DML'=>0,'DDL'=>0,'selects'=>count($out['events']),'schema_tables'=>count($out['schema']),'marked_staff'=>count($out['marked']['staff']??[]),'marked_department'=>count($out['marked']['department']??[]),'errors'=>$out['errors']],JSON_UNESCAPED_UNICODE),"\n";
