<?php
declare(strict_types=1);
require __DIR__.'/common.php';
try{
    $db=cpPdo();$dm=getenv('PILOT_LANE')==='C';$snapshot=[];$columns=[];$raw=[];
    foreach(['store_role','store_role_menu','store_menu','store_menu_api'] as $t){
        $count=(int)$db->query('SELECT COUNT(*) FROM yoshop_'.$t)->fetchColumn();
        if($count>10000){throw new RuntimeException('Frozen table-size bound');}
        $raw[$t]=cpRows($db,'SELECT * FROM yoshop_'.$t);
        $snapshot[$t]=cpDigest($raw[$t]);
        $columns[$t]=cpRows($db,$dm?"SELECT COLUMN_NAME,DATA_TYPE,NULLABLE FROM USER_TAB_COLUMNS WHERE TABLE_NAME='".strtoupper('yoshop_'.$t)."' ORDER BY COLUMN_ID":'SHOW COLUMNS FROM yoshop_'.$t);
        if(!$columns[$t]){throw new RuntimeException('Table schema missing');}
    }
    $tenant=10001;foreach($raw['store_role'] as $row){if($row['store_id']>0&&$row['parent_id']===0){$tenant=(int)$row['store_id'];break;}}
    $rootRoles=array_values(array_filter($raw['store_role'],static function($r)use($tenant){return $r['store_id']===$tenant&&$r['parent_id']===0;}));
    $out=['lane'=>getenv('PILOT_LANE'),'tenant'=>$tenant,'columns'=>$columns,'before'=>$snapshot,'natural_role_roots'=>count($rootRoles),'root_role_name'=>$rootRoles[0]['role_name']??null];
    $path=getenv('PILOT_RUNTIME').'/preflight-private.json';file_put_contents($path,json_encode($out,JSON_UNESCAPED_UNICODE|JSON_PRESERVE_ZERO_FRACTION|JSON_THROW_ON_ERROR));chmod($path,0600);
    echo json_encode(['status'=>'pass','lane'=>$out['lane'],'natural_role_roots'=>$out['natural_role_roots'],'snapshot'=>$snapshot,'dml'=>0,'ddl'=>0]),PHP_EOL;
}catch(Throwable $e){echo json_encode(['status'=>'fail','class'=>get_class($e),'code'=>(string)$e->getCode(),'file'=>basename($e->getFile()),'line'=>$e->getLine()]),PHP_EOL;exit(1);}
