<?php

declare(strict_types=1);

// SELECT-only. Reuses the frozen local-MySQL/nonproduction-DM boundary gate.
$lane = (string)getenv('CDX_NEXT5_LANE');
$preflight = $lane === 'C'
    ? '/tmp/zhct-next5-readonly-20261004/preflight_next5.php'
    : '/workspace/zhct/zhctprompt/work_store/apifox/2026-09-30-dm8-interface-acceptance/parallel-store-next5-readonly/preflight_next5.php';
if (!in_array($lane, ['A', 'B', 'C'], true)
    || !is_file($preflight) || is_link($preflight)
    || hash_file('sha256', $preflight)
        !== '8f262f3645d6c7e082dc5a2d7c32d893d32eb91a3dd2365f7d88cec0db25c4d6') {
    throw new RuntimeException('Nutrition source boundary preflight absent or drifted');
}
$argv[1] = '--preflight';
require $preflight;

$scalar = static function (string $sql, array $args = []) use ($db) {
    $stmt = $db->prepare($sql);
    $stmt->execute($args);
    return $stmt->fetchColumn();
};
$summary = [];
foreach (['nutrition_consume', 'nutrition_staff', 'nutrition_scheme',
    'nutrition_scheme_ext', 'staff'] as $name) {
    $summary[$name] = (int)$scalar('SELECT COUNT(*) FROM ' . $table($name));
}
$summary['visible_staff_with_consumes'] = (int)$scalar(
    'SELECT COUNT(DISTINCT nc.STAFF_UUID) FROM ' . $table('nutrition_consume')
    . ' nc JOIN ' . $table('staff') . ' s ON s.UUID=nc.STAFF_UUID WHERE s.IS_SHOW=1');
$summary['visible_staff_with_scheme'] = (int)$scalar(
    'SELECT COUNT(DISTINCT ns.STAFF_UUID) FROM ' . $table('nutrition_staff')
    . ' ns JOIN ' . $table('staff') . ' s ON s.UUID=ns.STAFF_UUID WHERE s.IS_SHOW=1');
$summary['max_consume_time'] = (string)$scalar(
    'SELECT MAX(CONSUME_TIME) FROM ' . $table('nutrition_consume'));
$summary['max_scheme_create_time'] = (string)$scalar(
    'SELECT MAX(CREATE_TIME) FROM ' . $table('nutrition_staff'));
$functions = [];
foreach ([
    'date_format' => "SELECT DATE_FORMAT('2026-10-04 12:34:56', '%Y-%m-%d %H:%i') FROM DUAL",
    'find_in_set' => "SELECT FIND_IN_SET('b', 'a,b,c') FROM DUAL",
    'if' => "SELECT IF(1=1, 1, 0) FROM DUAL",
] as $name => $sql) {
    try {
        $value = $scalar($sql);
        $functions[$name] = ['sql_ok' => true, 'value' => is_scalar($value) ? (string)$value : null];
    } catch (PDOException $e) {
        $functions[$name] = ['sql_ok' => false, 'sqlstate' => $e->getCode()];
    }
}
echo json_encode(['nutrition_source' => $summary,
    'function_probe' => $functions,
    'business_http' => 0, 'dml' => 0], JSON_UNESCAPED_SLASHES), PHP_EOL;
