<?php
/** CLI: 恢复上一版点检优化扩大修改范围的3张公共表；唯一参数为站点根目录。 */
use think\facade\Db;
function restoreCheckSharedTables() {
    $c=Db::connect()->getConfig();$prefix=$c['prefix'];
    if(!preg_match('/^[a-zA-Z0-9_]*$/D',$prefix))throw new RuntimeException('Invalid prefix');
    $names=['me_machine_list','me_base','team_base'];$before=[];$changes=[];
    // 先完整预检，避免缺表或已有外键时执行部分转换。
    foreach($names as $name){
        $table=$prefix.$name;$rows=Db::query('SHOW TABLE STATUS WHERE Name=?',[$table]);
        if(!$rows)throw new RuntimeException('Missing table: '.$table);
        $before[$name]=$rows[0]['Engine'];
        if(!in_array(strtoupper($before[$name]),['INNODB','MYISAM'],true))throw new RuntimeException('Unexpected engine, inspect before restoring: '.$table);
        $foreign=Db::query('SELECT CONSTRAINT_NAME FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA=? AND REFERENCED_TABLE_NAME IS NOT NULL AND (TABLE_NAME=? OR REFERENCED_TABLE_NAME=?)',[$c['database'],$table,$table]);
        if($foreign)throw new RuntimeException('Foreign keys found, cannot restore automatically: '.$table);
    }
    foreach($names as $name){
        $table=$prefix.$name;
        if(strtoupper($before[$name])!=='MYISAM'){Db::execute("ALTER TABLE `$table` ENGINE=MyISAM");$changes[]=$table.': MyISAM';}
    }
    // 只删除本次新增、名称及字段完全匹配的设备列表索引，不碰其他索引。
    $table=$prefix.'me_machine_list';$fields=[];
    foreach(Db::query("SHOW INDEX FROM `$table`") as $index)if($index['Key_name']==='idx_check_devices')$fields[]=$index['Column_name'];
    if($fields===['line','status','is_check','type','id']){Db::execute("ALTER TABLE `$table` DROP INDEX idx_check_devices");$changes[]=$table.': removed idx_check_devices';}
    return ['database'=>$c['database'],'applied'=>true,'previousEngines'=>$before,'changes'=>$changes,'restoredEngine'=>'MyISAM'];
}
if(PHP_SAPI!=='cli' || realpath($_SERVER['SCRIPT_FILENAME']??'')!==__FILE__)return;
$root=$argv[1]??'D:/phpstudy_pro/WWW/cqoms.com';require rtrim($root,'/\\').'/vendor/autoload.php';
$app=new \think\App(rtrim($root,'/\\').'/');$app->initialize();
echo json_encode(restoreCheckSharedTables(),JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT),PHP_EOL;
