<?php

declare(strict_types=1);

// Read-only A/B/C source preflight and gated actual HTTP checks.
$lane = (string)getenv('CDX_MACHINE2_LANE');
$action = (string)($argv[1] ?? '');
$targets = [
    'A' => ['/tmp/zhct-http-store-a.l5omH8', 'http://127.0.0.1:18097', 21023, 'mysql'],
    'B' => ['/tmp/zhct-http-store-mysql.dQTTBP', 'http://127.0.0.1:18081', 10001, 'mysql'],
    'C' => ['/tmp/zhct-dm-poc-20260928.fcpiiN/store', 'http://127.0.0.1:18080', 112175, 'dm'],
];
if (!isset($targets[$lane])
    || !in_array($action, ['--preflight', '--execute-dish', '--execute-order'], true)
    || ($action !== '--preflight'
        && ((string)getenv('CDX_MACHINE2_EXECUTE') !== 'APPROVED_MACHINE2_READONLY_V1'
            || (string)getenv('CDX_MACHINE2_SHA') !== hash_file('sha256', __FILE__)))) {
    fwrite(STDERR, "Machine read2 execution disabled\n");
    exit(78);
}
[$root, $base, $pid, $dialect] = $targets[$lane];
$sourceShas = [
    'application/api/controller/OrderMachine.php' => '7d54990994b6f6dbb36a4e66461f136c568d7c9a673a7d8741bc92b058fc11ca',
    'application/api/service/OrderMachineDishes.php' => 'f19a48f139a2c515ee07f636445fedf43fd2213ada95235b22ff3e5c58eec319',
    'application/api/service/OrderMachineOrder.php' => $lane === 'A'
        ? '5a4c8eadccae2789c2fd42fb68a0ba55771524031a877958ff42a0b70b49aba9'
        : '40385c2e05ad9f8abcdfb14e5cb0e7dce442be0bbc9e71bbffad9e26f898734c',
    'application/common/enum/dishes/Nutrient.php' => '608b5d1d9665500af7e3e18da217210385b27e0d827d713268b61dbab693b343',
    'application/common/Common.php' => '49e2eab5fdc17e514f9420418b4cc281b92edb560b99f7cc62935011138dfeb4',
];
if ((string)getenv('POC_APP_ROOT') !== $root
    || (string)getenv('POC_BASE_URL') !== $base
    || (string)getenv('POC_DIALECT') !== $dialect || is_link($root)) {
    throw new RuntimeException('Machine read2 approved runtime mismatch');
}
foreach ($sourceShas as $file => $sha) {
    if (hash_file('sha256', $root . '/' . $file) !== $sha) {
        throw new RuntimeException('Machine read2 approved source mismatch: ' . $file);
    }
}
$cmdline = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
$environment = (string)@file_get_contents('/proc/' . $pid . '/environ');
$children = (string)@file_get_contents('/proc/' . $pid . '/task/' . $pid . '/children');
$boundary = json_decode((string)@file_get_contents($base . '/__poc_boundary'), true);
$port = (int)parse_url($base, PHP_URL_PORT);
$hex = strtoupper(str_pad(dechex($port), 4, '0', STR_PAD_LEFT));
$inode = '';
foreach (@file('/proc/net/tcp', FILE_IGNORE_NEW_LINES) ?: [] as $line) {
    $parts = preg_split('/\s+/', trim($line));
    if (($parts[1] ?? '') === '0100007F:' . $hex && ($parts[3] ?? '') === '0A') {
        $inode = (string)($parts[9] ?? '');
        break;
    }
}
$ownsPort = false;
if ($inode !== '') {
    foreach (@scandir('/proc/' . $pid . '/fd') ?: [] as $fd) {
        if ($fd !== '.' && $fd !== '..'
            && @readlink('/proc/' . $pid . '/fd/' . $fd) === 'socket:[' . $inode . ']') {
            $ownsPort = true;
            break;
        }
    }
}
$multiWorker = preg_match('/(?:^|\x00)PHP_CLI_SERVER_WORKERS=(\d+)(?:\x00|$)/',
    $environment, $match) && (int)$match[1] > 1;
if (strpos($cmdline, '127.0.0.1:' . $port) === false
    || strpos($cmdline, $root . '/public') === false
    || $environment === '' || trim($children) !== '' || !$ownsPort || $multiWorker
    || !is_array($boundary) || empty($boundary['external_stubs'])
    || empty($boundary['redis_isolated']) || !empty($boundary['real_queue'])) {
    throw new RuntimeException('Machine read2 isolated HTTP boundary absent');
}
$runtime = (static function (string $path): array {
    $value = require $path;
    if (!is_array($value)) throw new RuntimeException('Invalid machine2 DB config');
    return $value;
})($root . '/application/database.php');
if ((string)($runtime['prefix'] ?? '') !== 'ydy_') {
    throw new RuntimeException('Machine2 table prefix mismatch');
}
if ($dialect === 'mysql') {
    $local = (static function (): array {
        $value = require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
        if (!is_array($value)) throw new RuntimeException('Invalid code local DB config');
        return $value;
    })();
    if ((string)($runtime['type'] ?? '') !== 'mysql') {
        throw new RuntimeException('Machine2 MySQL driver mismatch');
    }
    foreach (['hostname', 'database', 'username', 'password'] as $key) {
        if (($runtime[$key] ?? null) !== ($local[$key] ?? null)) {
            throw new RuntimeException('Machine2 runtime differs from code local');
        }
    }
    if ((int)($runtime['hostport'] ?? 3306) !== (int)($local['hostport'] ?? 3306)) {
        throw new RuntimeException('Machine2 MySQL port mismatch');
    }
    $dsn = 'mysql:host=' . $runtime['hostname'] . ';port='
        . (int)($runtime['hostport'] ?? 3306) . ';dbname=' . $runtime['database']
        . ';charset=' . (string)($runtime['charset'] ?? 'utf8');
    $username = (string)$runtime['username'];
    $password = (string)$runtime['password'];
} else {
    if ((string)($runtime['type'] ?? '') !== 'app\\cores\\database\\Dm'
        || (string)getenv('POC_HOST') !== '127.0.0.1'
        || (string)getenv('POC_PORT') !== '5237'
        || strtoupper((string)getenv('POC_SCHEMA')) !== 'ZHCT_APP'
        || strtoupper((string)getenv('POC_USER')) !== 'ZHCT_APP') {
        throw new RuntimeException('Machine2 DM target mismatch');
    }
    foreach (['hostname' => 'POC_HOST', 'hostport' => 'POC_PORT',
        'database' => 'POC_SCHEMA', 'username' => 'POC_USER',
        'password' => 'POC_PASSWORD'] as $key => $envKey) {
        if ((string)($runtime[$key] ?? '') !== (string)getenv($envKey)) {
            throw new RuntimeException('Machine2 DM worker context mismatch');
        }
    }
    $dsn = 'dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';
    $username = (string)getenv('POC_USER');
    $password = (string)getenv('POC_PASSWORD');
    $machineId = trim((string)@file_get_contents('/etc/machine-id'));
    if ($machineId === '' || gethostname() === false
        || hash('sha256', gethostname() . '|' . $machineId)
            !== 'd56d81988bb0f106946cce91c608fdd0ef1116e5150b23376ea87e086eace4b9') {
        throw new RuntimeException('Machine2 DM host mismatch');
    }
    $lines = [];
    $code = 0;
    @exec('/usr/sbin/ss -ltnp 2>/dev/null', $lines, $code);
    $localDm = false;
    if ($code === 0) {
        foreach ($lines as $line) {
            if (preg_match('/\*:5237\s+.*users:\(\("dmserver",pid=(\d+),/', $line, $match)) {
                $exe = @readlink('/proc/' . $match[1] . '/exe');
                $localDm = is_string($exe) && basename($exe) === 'dmserver';
                break;
            }
        }
    }
    if (!$localDm) throw new RuntimeException('Machine2 DM listener not local');
}
$pdo = new PDO($dsn, $username, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_TIMEOUT => 5]);
if ($dialect === 'mysql') {
    $identity = (string)$pdo->query(
        "SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())"
    )->fetchColumn();
    $approved = '003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401';
} else {
    $schema = (string)$pdo->query(
        "SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL"
    )->fetchColumn();
    if (strtoupper($schema) !== 'ZHCT_APP') throw new RuntimeException('Machine2 DM schema mismatch');
    $identity = 'ZHCT_APP|5237|' . $schema;
    $approved = 'bc98485aed26beab348770a82ae38dbf922b04ab88a210cd7282c4caf0156194';
}
if (!hash_equals($approved, hash('sha256', $identity))) {
    throw new RuntimeException('Machine2 approved DB identity mismatch');
}
date_default_timezone_set('PRC');
$prefix = $dialect === 'dm' ? 'YDY_' : 'ydy_';
$today = date('Y-m-d');
$dateFrom = date('Y-m-d 00:00:00', strtotime('-2 day'));
$stmt = $pdo->prepare('SELECT d.ID,d.UUID FROM ' . $prefix . 'dishes d'
    . ' INNER JOIN ' . $prefix . 'recipes r ON r.DISHES_UUID=d.UUID'
    . ' WHERE r.MENU_DATE=? AND d.IS_DEL=1 AND d.STATUS=1 ORDER BY d.ID ASC');
$stmt->execute([$today]);
$dish = $stmt->fetch(PDO::FETCH_ASSOC);
$dish = $dish === false ? null : array_change_key_case($dish, CASE_LOWER);
$stmt = $pdo->prepare('SELECT mo.ID,mo.ORDER_NO FROM ' . $prefix . 'meal_order mo'
    . ' INNER JOIN ' . $prefix . 'meal_order_pickup p ON p.MEAL_ORDER_ID=mo.ID'
    . ' WHERE mo.IS_DELETE=0 AND mo.PAY_STATUS=20 AND mo.CREATE_TIME>=?'
    . ' ORDER BY mo.ID DESC');
$stmt->execute([$dateFrom]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);
$order = $order === false ? null : array_change_key_case($order, CASE_LOWER);
$mealAt = static function (array $stall, string $time): int {
    foreach ([1 => ['morning_start', 'morning_end'],
        2 => ['noon_start', 'noon_end'], 3 => ['night_start', 'night_end']] as $meal => $fields) {
        $start = (string)($stall[$fields[0]] ?? '') . ':00';
        $end = (string)($stall[$fields[1]] ?? '') . ':59';
        if ($time >= $start && $time <= $end) return $meal;
    }
    return 4;
};
$stmt = $pdo->prepare('SELECT p.RESTAURANT_ID,p.MEAL_TIMES,p.PREPARE_STATUS,p.PICKUP_NO,'
    . 'r.MORNING_START,r.MORNING_END,r.NOON_START,r.NOON_END,r.NIGHT_START,r.NIGHT_END'
    . ' FROM ' . $prefix . 'meal_order_pickup p'
    . ' INNER JOIN ' . $prefix . 'restaurants r ON r.ID=p.RESTAURANT_ID'
    . ' WHERE p.MEAL_DATE=? AND p.PREPARE_STATUS IN (10,20)'
    . " AND p.PICKUP_NO<>'' AND r.IS_DELETE=2 AND r.STATUS=1"
    . ' ORDER BY p.ID DESC');
$stmt->execute([$today]);
$queue = null;
$rowsScanned = 0;
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
    $rowsScanned++;
    if ($rowsScanned > 500) throw new RuntimeException('Machine2 queue source scan bound');
    $row = array_change_key_case($row, CASE_LOWER);
    if ((int)$row['meal_times'] === $mealAt($row, date('H:i:s'))) {
        $queue = $row;
        break;
    }
}
$result = [
    'lane' => $lane, 'dialect' => $dialect, 'date' => $today,
    'natural_active_today_dish' => $dish !== null,
    'dish_uuid_sha' => $dish === null ? null : hash('sha256', (string)$dish['uuid']),
    'natural_recent_paid_pickup_order' => $order !== null,
    'order_no_sha' => $order === null ? null : hash('sha256', (string)$order['order_no']),
    'order_no_four_digits' => $order === null ? null
        : preg_match('/^\d{4}$/D', (string)$order['order_no']) === 1,
    'natural_current_meal_nonempty_pickup_queue' => $queue !== null,
    'pickup_restaurant_id' => $queue === null ? null : (int)$queue['restaurant_id'],
    'pickup_rows_scanned' => $rowsScanned,
    'http_executed' => false,
];
if ($action === '--preflight') {
    echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit(0);
}
$toText = static function ($value): ?string {
    if ($value === null) return null;
    return is_resource($value) ? (string)stream_get_contents($value) : (string)$value;
};
$normalize = static function ($stmt, int $bound) use ($toText): array {
    $rows = [];
    while (($row = $stmt->fetch(PDO::FETCH_ASSOC)) !== false) {
        $normal = [];
        foreach (array_change_key_case($row, CASE_LOWER) as $key => $fieldValue) {
            $normal[$key] = $toText($fieldValue);
        }
        $rows[] = $normal;
        if (count($rows) > $bound) throw new RuntimeException('Machine2 source bound exceeded');
    }
    return $rows;
};
$http = static function (string $path, string $method, array $params) use (
    $base, $root, $pid): array {
    $port = (int)parse_url($base, PHP_URL_PORT);
    $cmdline = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
    if (strpos($cmdline, '127.0.0.1:' . $port) === false
        || strpos($cmdline, $root . '/public') === false) {
        throw new RuntimeException('Machine2 HTTP runtime drift');
    }
    $form = http_build_query($params, '', '&', PHP_QUERY_RFC3986);
    $context = stream_context_create(['http' => [
        'method' => $method,
        'header' => $method === 'POST'
            ? "Content-Type: application/x-www-form-urlencoded\r\nAccept: application/json\r\n"
            : "Accept: application/json\r\n",
        'content' => $method === 'POST' ? $form : '',
        'timeout' => 20, 'ignore_errors' => true,
    ]]);
    $url = $base . $path . ($method === 'GET' ? '?' . $form : '');
    $start = microtime(true);
    $stream = @fopen($url, 'rb', false, $context);
    if (!$stream) throw new RuntimeException('Machine2 HTTP open failed');
    $headers = $http_response_header ?? [];
    $body = stream_get_contents($stream, 262145);
    fclose($stream);
    if (!is_string($body) || strlen($body) > 262144
        || strpos((string)($headers[0] ?? ''), ' 200 ') === false) {
        throw new RuntimeException('Machine2 HTTP status or 256 KiB bound mismatch');
    }
    $json = json_decode($body, true);
    if (!is_array($json)) throw new RuntimeException('Machine2 HTTP JSON invalid');
    return [$json, (int)round((microtime(true) - $start) * 1000),
        strlen($body), hash('sha256', $body)];
};

if ($action === '--execute-dish') {
    if ($dish === null) throw new RuntimeException('No natural active today dish');
    $source = static function () use ($pdo, $prefix, $dish, $normalize): array {
        $stmt = $pdo->prepare('SELECT * FROM ' . $prefix . 'dishes WHERE ID=? AND UUID=?');
        $stmt->execute([(int)$dish['id'], (string)$dish['uuid']]);
        $dishes = $normalize($stmt, 1);
        if (count($dishes) !== 1 || (int)$dishes[0]['is_del'] !== 1
            || (int)$dishes[0]['status'] !== 1) {
            throw new RuntimeException('Dish fixture drift');
        }
        $stmt = $pdo->prepare('SELECT ID,NAME,COLOR FROM ' . $prefix . 'dishes_tag'
            . ' WHERE DISHES_ID=? AND IS_DELETE=0 ORDER BY ID ASC');
        $stmt->execute([(int)$dish['id']]);
        $tags = $normalize($stmt, 100);
        $stmt = $pdo->prepare('SELECT ID,ENUM_TYPE,ENUM_KEY,ENUM_NAME FROM '
            . $prefix . 'config_enum WHERE IS_DELETE=0 AND'
            . ' ((ENUM_TYPE=3 AND ENUM_KEY=?) OR (ENUM_TYPE=4 AND ENUM_KEY=?))'
            . ' ORDER BY ID ASC');
        $stmt->execute([(string)$dishes[0]['unit'], (string)$dishes[0]['cook_method']]);
        $enums = $normalize($stmt, 20);
        return [$dishes[0], $tags, $enums];
    };
    $before = $source();
    $beforeSha = hash('sha256', serialize($before));
    [$row, $tags, $enums] = $before;
    [$success, $ms, $bytes, $responseSha] = $http(
        '/api/orderMachine/dishDetail', 'POST', ['dishes_uuid' => (string)$dish['uuid']]);
    if (array_keys($success) !== ['code', 'message', 'data']
        || ($success['code'] ?? null) !== 0
        || ($success['message'] ?? null) !== '获取成功'
        || !is_array($success['data'] ?? null)) {
        throw new RuntimeException('Dish positive envelope mismatch');
    }
    $data = $success['data'];
    if (array_keys($data) !== ['uuid', 'name', 'file_path', 'price', 'unit',
        'unit_name', 'weight', 'tag', 'nutrient_elements']
        || !is_string($data['uuid']) || $data['uuid'] !== (string)$dish['uuid']
        || !is_string($data['name']) || $data['name'] !== (string)$row['name']
        || !is_string($data['file_path'])
        || (!is_int($data['price']) && !is_float($data['price']))
        || abs((float)$data['price'] - (float)$row['price']) > 0.000001
        || !is_int($data['unit']) || $data['unit'] !== (int)$row['unit']
        || !is_string($data['unit_name'])
        || (!is_int($data['weight']) && !is_float($data['weight']))
        || abs((float)$data['weight'] - (float)$row['weight']) > 0.000001
        || !is_array($data['tag']) || count($data['tag']) !== count($tags)
        || !is_array($data['nutrient_elements'])
        || count($data['nutrient_elements']) !== 16) {
        throw new RuntimeException('Dish positive core contract mismatch');
    }
    $path = str_replace('\\', '/', (string)($row['file_path'] ?? ''));
    if ($path !== '' && substr($data['file_path'], -strlen($path)) !== $path) {
        throw new RuntimeException('Dish image source mismatch');
    }
    $unitName = '';
    foreach ($enums as $enum) {
        if ((int)$enum['enum_type'] === 3 && (string)$enum['enum_key'] === (string)$row['unit']) {
            $unitName = (string)$enum['enum_name'];
            break;
        }
    }
    if ($data['unit_name'] !== $unitName) throw new RuntimeException('Dish unit enum mismatch');
    foreach ($tags as $index => $tag) {
        $actual = $data['tag'][$index] ?? null;
        if (!is_array($actual) || array_keys($actual) !== ['name', 'color']
            || !is_string($actual['name']) || $actual['name'] !== (string)$tag['name']
            || !is_string($actual['color']) || $actual['color'] !== (string)$tag['color']) {
            throw new RuntimeException('Dish nested tag mismatch');
        }
    }
    if (!defined('APP_PATH')) define('APP_PATH', $root . '/application');
    require_once $root . '/application/common/enum/EnumBasics.php';
    require_once $root . '/application/common/enum/dishes/Nutrient.php';
    $nutrients = \app\common\enum\dishes\Nutrient::data();
    $order = [0, 1, 2, 3, 7, 8, 14, 20, 21, 22, 23, 24, 25, 26, 29, 30];
    $valueTypes = [];
    foreach ($order as $index => $key) {
        $item = $nutrients[$key];
        $actual = $data['nutrient_elements'][$index] ?? null;
        $field = (string)$item['field'];
        $unit = (string)$item['unit'];
        if (in_array($unit, ['mg', 'ug', 'ugRE'], true)) $unit = '微克';
        $raw = (float)($row[$field] ?? 0);
        $weight = (float)$row['weight'];
        $expected = $weight > 0 ? round($raw * 100 / $weight, 2) : $raw;
        if (!is_array($actual)
            || array_keys($actual) !== ['field', 'name', 'value', 'unit']
            || $actual['field'] !== $field || $actual['name'] !== $item['name']
            || $actual['unit'] !== $unit
            || (!is_int($actual['value']) && !is_float($actual['value']))
            || abs((float)$actual['value'] - $expected) > 0.000001) {
            throw new RuntimeException('Dish nutrient source/shape mismatch: ' . $field);
        }
        $valueTypes[gettype($actual['value'])] = true;
    }
    [$missing] = $http('/api/orderMachine/dishDetail', 'POST', []);
    [$unknown] = $http('/api/orderMachine/dishDetail', 'POST',
        ['dishes_uuid' => 'CDX-NOT-FOUND-' . bin2hex(random_bytes(12))]);
    if (($missing['code'] ?? null) !== 1
        || ($missing['message'] ?? null) !== '菜品UUID不能为空'
        || ($missing['data'] ?? null) !== []
        || ($unknown['code'] ?? null) !== 1
        || ($unknown['message'] ?? null) !== '菜品不存在'
        || ($unknown['data'] ?? null) !== []) {
        throw new RuntimeException('Dish invalid UUID rejection mismatch');
    }
    $afterSha = hash('sha256', serialize($source()));
    if (!hash_equals($beforeSha, $afterSha)) {
        throw new RuntimeException('Dish source changed during read-only HTTP');
    }
    $result['http_executed'] = true;
    $result += [
        'route' => 'POST /api/orderMachine/dishDetail',
        'positive_code' => 0, 'missing_code' => 1, 'unknown_code' => 1,
        'tag_count' => count($tags), 'nutrient_count' => count($order),
        'nutrient_json_number_types' => array_keys($valueTypes),
        'price_json_type' => gettype($data['price']),
        'weight_json_type' => gettype($data['weight']),
        'source_sha' => $beforeSha, 'source_unchanged' => true,
        'response_bytes' => $bytes, 'response_sha' => $responseSha,
        'positive_http_ms' => $ms,
    ];
    echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit(0);
}
if ($order === null || preg_match('/^\d{4}$/D', (string)$order['order_no'])) {
    throw new RuntimeException('No bounded natural exact-number paid pickup order');
}
$orderSource = static function () use ($pdo, $prefix, $order, $dateFrom, $normalize): array {
    $stmt = $pdo->prepare('SELECT mo.ID,mo.ORDER_NO,mo.USER_MOBILE,mo.USER_NAME,'
        . 'mo.PAY_PRICE,mo.PAY_TIME,mo.MEAL_DATE,'
        . 'r.NAME AS RESTAURANT_NAME,p.PICKUP_NO,p.PREPARE_STATUS,'
        . 'u.MOBILE AS USER_MOBILE_REAL,u.NAME AS USER_NAME_REAL'
        . ' FROM ' . $prefix . 'meal_order mo'
        . ' INNER JOIN ' . $prefix . 'meal_order_pickup p ON p.MEAL_ORDER_ID=mo.ID'
        . ' LEFT JOIN ' . $prefix . 'restaurants r ON r.ID=mo.RESTAURANT_ID'
        . ' LEFT JOIN ' . $prefix . 'user u ON u.ID=mo.USER_ID'
        . ' WHERE mo.IS_DELETE=0 AND mo.PAY_STATUS=20 AND mo.CREATE_TIME>=?'
        . ' AND mo.ORDER_NO=? ORDER BY mo.ID DESC');
    $stmt->execute([$dateFrom, (string)$order['order_no']]);
    return $normalize($stmt, 50);
};
$before = $orderSource();
if (!$before) throw new RuntimeException('Order positive source drift');
$beforeSha = hash('sha256', serialize($before));
[$success, $ms, $bytes, $responseSha] = $http('/api/orderMachine/orderList',
    'POST', ['keyword' => (string)$order['order_no']]);
if (array_keys($success) !== ['code', 'message', 'data']
    || ($success['code'] ?? null) !== 0
    || ($success['message'] ?? null) !== '获取成功'
    || !is_array($success['data'] ?? null)
    || count($success['data']) !== count($before)) {
    throw new RuntimeException('Order positive envelope/count mismatch');
}
$statuses = [];
foreach ($before as $index => $source) {
    $actual = $success['data'][$index] ?? null;
    $mobile = (string)($source['user_mobile_real'] ?? '');
    if ($mobile === '') $mobile = (string)($source['user_mobile'] ?? '');
    $name = (string)($source['user_name_real'] ?? '');
    if ($name === '') $name = (string)($source['user_name'] ?? '');
    $status = (int)$source['prepare_status'];
    if ((string)($source['meal_date'] ?? '') !== ''
        && (string)$source['meal_date'] < $today) {
        $status = 30;
    } elseif ($status !== 20 && $status !== 30) {
        $status = 10;
    }
    $statusName = [10 => '备餐中', 20 => '待取餐', 30 => '已完成'][$status];
    if (!is_array($actual)
        || array_keys($actual) !== ['id', 'pickup_no', 'restaurant_name',
            'order_amount', 'pay_time', 'order_no', 'user_mobile', 'user_name',
            'order_status', 'order_status_value']
        || !is_int($actual['id']) || $actual['id'] !== (int)$source['id']
        || !is_string($actual['pickup_no'])
        || $actual['pickup_no'] !== (string)($source['pickup_no'] ?? '')
        || !is_string($actual['restaurant_name'])
        || $actual['restaurant_name'] !== (string)($source['restaurant_name'] ?? '')
        || !is_string($actual['order_amount'])
        || $actual['order_amount'] !== number_format((float)$source['pay_price'], 2, '.', '')
        || !is_string($actual['pay_time'])
        || $actual['pay_time'] !== (string)($source['pay_time'] ?? '')
        || !is_string($actual['order_no'])
        || $actual['order_no'] !== (string)$source['order_no']
        || !is_string($actual['user_mobile']) || $actual['user_mobile'] !== $mobile
        || !is_string($actual['user_name']) || $actual['user_name'] !== $name
        || !is_string($actual['order_status'])
        || $actual['order_status'] !== $statusName
        || !is_int($actual['order_status_value'])
        || $actual['order_status_value'] !== $status) {
        throw new RuntimeException('Order source/JSON contract mismatch');
    }
    $statuses[$status] = true;
}
[$missing] = $http('/api/orderMachine/orderList', 'POST', []);
if (array_keys($missing) !== ['code', 'message', 'data']
    || ($missing['code'] ?? null) !== 1
    || ($missing['message'] ?? null) !== '关键词不能为空'
    || ($missing['data'] ?? null) !== []) {
    throw new RuntimeException('Order missing-keyword rejection mismatch');
}
$afterSha = hash('sha256', serialize($orderSource()));
if (!hash_equals($beforeSha, $afterSha)) {
    throw new RuntimeException('Order source changed during read-only HTTP');
}
$result['http_executed'] = true;
$result += [
    'route' => 'POST /api/orderMachine/orderList',
    'positive_code' => 0, 'missing_code' => 1,
    'matched_orders' => count($before), 'status_values' => array_keys($statuses),
    'order_amount_json_type' => gettype($success['data'][0]['order_amount']),
    'source_sha' => $beforeSha, 'source_unchanged' => true,
    'response_bytes' => $bytes, 'response_sha' => $responseSha,
    'positive_http_ms' => $ms,
];
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
