<?php
declare(strict_types=1);
$path=parse_url($_SERVER['REQUEST_URI']??'',PHP_URL_PATH);
if (!preg_match('#^/(store|terminal)/store\.Habit/(detail|setHabit|detailRpe|setRpe)$#D',(string)$path)
    && $path!=='/__poc_boundary') { http_response_code(403);echo '{"denied":true}';return; }
$method=$_SERVER['REQUEST_METHOD']??'';
if($path!=='/__poc_boundary' && $method!=='POST'
    && !($method==='GET'&&preg_match('#^/terminal/store\.Habit/(detail|detailRpe)$#D',(string)$path))){
    http_response_code(403);echo '{"denied":true}';return;
}
$root=(string)getenv('CATEGORY_ROOT');$runtime=(string)getenv('CATEGORY_RUNTIME');
ini_set('log_errors','1');ini_set('error_log',$runtime.'/private-php-error.log');
$_SERVER['SCRIPT_FILENAME']=$root.'/public/index.php';$_SERVER['SCRIPT_NAME']='/index.php';$_SERVER['PHP_SELF']='/index.php';
define('TP_ENV','poc');define('BUSINESS','aizhct');define('ENTERPRISE_NO','10001');
require $root.'/vendor/autoload.php';
// Composer in the historical runtime has absolute source paths. Use current,
// checksummed source in this private worker without editing the shared runtime.
spl_autoload_register(static function(string $class)use($root):void{
    foreach(['app\\'=>'app/','cores\\'=>'cores/'] as $prefix=>$directory){
        if(strpos($class,$prefix)!==0)continue;
        $file=$root.'/'.$directory.str_replace('\\','/',substr($class,strlen($prefix))).'.php';
        if(is_file($file))require $file;
    }
},true,true);
require __DIR__.'/habit_external_stubs.php';
if($path==='/__poc_boundary'){
    header('Content-Type: application/json');echo json_encode(['external_stubs'=>
        class_exists(\app\common\Serve::class,false)&&class_exists(\app\common\UserApi::class,false),
        'private_cache'=>true,'allowlist'=>'habit-only','queue_capture_mode'=>\app\common\Serve::CAPTURE_MODE,'source_root'=>basename($root)]);return;
}
$scenario=$_SERVER['HTTP_X_PILOT_SCENARIO']??'';
if(!preg_match('/^PILOT_HAB_[A-Z0-9_]{1,60}$/D',$scenario)){http_response_code(403);echo '{"denied":true}';return;}
require __DIR__.'/SqlCoverageRecorder.php';
$app=new \think\App($root);$app->setEnvName('poc');$app->setRuntimePath($runtime.'/runtime/');$app->initialize();
$hostMap=['store.habit-test.invalid'=>2147000421,'terminal.habit-test.invalid'=>2147000422];
$app->env->set('store.host',$hostMap);
$expectedTenant=$hostMap[$app->request->host()]??null;
if($expectedTenant===null||\getStoreId()!==$expectedTenant){http_response_code(403);echo '{"tenant_denied":true}';return;}
$config=$app->config->get('database');
foreach($config['connections'] as &$connection){$connection['trigger_sql']=true;$connection['debug']=false;}unset($connection);
$app->config->set($config,'database');$app->db->setConfig($app->config);
$app->config->set(['default'=>'file','stores'=>['file'=>['type'=>'File','path'=>$runtime.'/cache/','prefix'=>'','expire'=>0]]],'cache');
$app->instance('cache',new \think\Cache($app));
$log=$app->config->get('log');$log['close']=true;
foreach($log['channels'] as &$channel)$channel['close']=true;unset($channel);
$app->config->set($log,'log');
$app->instance(\think\exception\Handle::class,new class($app) extends \cores\ExceptionHandle {
    public function report(\Throwable $error):void {
        $frames=[];foreach($error->getTrace() as $frame)$frames[]=array_intersect_key($frame,array_flip(['file','line','class','function']));
        file_put_contents((string)getenv('CATEGORY_RUNTIME').'/private-error-location.json',json_encode([
            'class'=>get_class($error),'file'=>$error->getFile(),'line'=>$error->getLine(),'frames'=>$frames]));
    }
});
$headerToken=(string)$app->request->header('Access-Token','');
file_put_contents($runtime.'/private-auth-diagnostic.json',json_encode([
    'token_header_present'=>$headerToken!=='','cache_path'=>$app->config->get('cache.stores.file.path'),
    'token_cache_present'=>(bool)$app->cache->get($headerToken)]));
$recorder=new SqlCoverageRecorder($runtime.'/queries.jsonl',$root,$scenario);
$app->db->listen(static function($sql,$elapsed=null)use($recorder):void{
    if(strpos((string)$sql,'CONNECT:')===0)return;
    $recorder->observe($sql,$elapsed);
});register_shutdown_function([$recorder,'finish']);
$http=$app->http;$response=$http->run();$response->send();$http->end($response);
