<?php
/** CLI: 站点根目录为唯一参数；仅调整6张点检专用表，公共主档/字典表只读。 */
use think\facade\Db;
function optimizeToolsCheck($app) {
    $c=Db::connect()->getConfig();$p=$c['prefix'];
    if(!preg_match('/^[a-zA-Z0-9_]*$/D',$p))throw new RuntimeException('Invalid prefix');
    $changes=[];
    $indexes=[
        'me_check_list'=>['idx_check_type'=>['type','status','order','id']],
        'me_check_record'=>['idx_check_slot'=>['m_id','check_date','shift','status','check_id'],'idx_check_history'=>['mid','status','update','m_id'],'idx_check_mine'=>['mid','check_date','shift','status','m_id']],
        'me_check_issue'=>['idx_check_record'=>['check_id','id'],'idx_check_open'=>['status','check_id']],
        'me_check_issue_flow'=>[], 'me_check_issue_log'=>[], 'me_check_pause'=>[],
    ];
    // 在低峰暂停点检与基础数据导入后运行；DDL自动提交，不包在业务事务中。
    foreach($indexes as $name=>$wanted){
        $table=$p.$name;$rows=Db::query("SHOW TABLE STATUS WHERE Name=?",[$table]);
        if(!$rows)throw new RuntimeException('Missing table: '.$table);
        if(strtoupper($rows[0]['Engine'])!=='INNODB'){Db::execute("ALTER TABLE `$table` ENGINE=InnoDB");$changes[]=$table.': InnoDB';}
        $existing=[];foreach(Db::query("SHOW INDEX FROM `$table`") as $row)$existing[$row['Key_name']][]=$row['Column_name'];
        foreach($wanted as $key=>$fields){
            $covered=false;foreach($existing as $actual)if(array_slice($actual,0,count($fields))===$fields){$covered=true;break;}
            if($covered)continue;
            $quoted=array_map(function($field){return '`'.$field.'`';},$fields);
            $drop=isset($existing[$key])?"DROP INDEX `$key`, ":'';
            Db::execute("ALTER TABLE `$table` ".$drop."ADD INDEX `$key` (".implode(',',$quoted).")");$changes[]=$table.': '.$key;
        }
    }
    \app\mobile\service\CheckCatalog::invalidate();\app\mobile\service\CheckCatalog::names();$types=Db::name('me_check_list')->where('status',1)->distinct(true)->column('type');
    foreach($types as $type)\app\mobile\service\CheckCatalog::clauses($type);
    return ['database'=>$c['database'],'applied'=>true,'tables'=>array_keys($indexes),'changes'=>$changes,'warmedTypes'=>count($types)];
}
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(optimizeToolsCheck($app),JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT),PHP_EOL;
