<?php
declare(strict_types=1);

// Load the reviewed fixed WeekNew source privately; only zero-row SELECT/metadata.
require __DIR__ . '/c_readonly_preflight.php';
$stage = 'private_fixed_source_bootstrap';
foreach ($config as $key => $value) {
    if (strpos($key, 'POC_') === 0) putenv($key . '=' . $value);
}
define('TP_ENV', 'poc');
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
require $root . '/vendor/autoload.php';
(new \think\App($root))->setEnvName('poc')->initialize();
$class = \app\api\service\analysis\WeekNew::class;
if (class_exists($class, false)) {
    throw new RuntimeException('WeekNew loaded before private source');
}
require __DIR__ . '/WeekNew.fixed.private.php';
$expectedSha = (string)getenv('CDX_FIXED_WEEK_SHA');
if ($expectedSha === ''
    || hash_file('sha256', __DIR__ . '/WeekNew.fixed.private.php') !== $expectedSha) {
    throw new RuntimeException('Private source hash mismatch');
}
$service = new $class();
$method = new ReflectionMethod($class, 'scopedMealInfos');
$method->setAccessible(true);
$stage = 'aliased_query_preview';
$previewQuery = $method->invoke($service);
$sql = $previewQuery->field('meal_infos.id')
    ->whereRaw('1=0')->fetchSql(true)->select();
if (!is_string($sql)) throw new RuntimeException('SQL preview unavailable');
$lower = strtolower($sql);
$aliasQualified = strpos($lower, 'meal_infos.store_id') !== false;
$physicalQualified = strpos($lower, 'yoshop_meal_infos.store_id') !== false;
if (!$aliasQualified || $physicalQualified) {
    throw new RuntimeException('Tenant SQL qualifier still incorrect');
}
$stage = 'aliased_zero_row_execution';
$executeQuery = $method->invoke($service);
$rows = $executeQuery->field('meal_infos.id')
    ->whereRaw('1=0')->select()->toArray();
if (count($rows) !== 0) throw new RuntimeException('Expected zero rows');
echo json_encode(['status' => 'private-week-helper-c-zero-row-pass',
    'private_source_sha_match' => true,
    'tenant_uses_meal_infos_alias' => $aliasQualified,
    'tenant_uses_physical_table_after_alias' => $physicalQualified,
    'zero_row_queryable' => true,
    'business_rows_read' => 0, 'writes' => 0,
], JSON_UNESCAPED_SLASHES), PHP_EOL;
