<?php

declare(strict_types=1);

// Nonproduction electronic-menu A/B/C harness. The default mode is SELECT-only.
$lane = (string)getenv('CDX_EBOARD_LANE');
$action = (string)($argv[1] ?? '');
$executeDevice = $action === '--execute-device';
$executeCopy = $action === '--execute-copy';
$executeUpdate = $action === '--execute-update';
$executeExpired = $action === '--execute-expired';
$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-core', '--execute-device',
            '--execute-copy', '--execute-update', '--execute-expired'], true)
    || ($action !== '--preflight'
        && ((string)getenv('CDX_EBOARD_EXECUTE')
                !== ($executeDevice ? 'ROOT_APPROVED_DEVICE_V1'
                    : ($executeCopy ? 'ROOT_APPROVED_COPY_V1'
                        : ($executeUpdate ? 'ROOT_APPROVED_UPDATE_V1'
                            : ($executeExpired ? 'ROOT_APPROVED_EXPIRED_V1'
                                : 'ROOT_APPROVED_CORE_V1'))))
            || (string)getenv('CDX_EBOARD_APPROVED_SHA') !== hash_file('sha256', __FILE__)))) {
    fwrite(STDERR, "Execution disabled without exact isolated target and approval\n");
    exit(78);
}
[$root, $base, $pid, $dialect] = $targets[$lane];
if ((string)getenv('POC_APP_ROOT') !== $root
    || (string)getenv('POC_BASE_URL') !== $base
    || (string)getenv('POC_DIALECT') !== $dialect
    || is_link($root) || !is_file($root . '/application/database.php')) {
    throw new RuntimeException('Isolated runtime target mismatch');
}
$expectedServiceHash = $lane === 'A'
    ? '525caaeb63bc83a4f401de077b0784de49b98572b3b7732577b143138d9e7e28'
    : '179869c96cfdaf5e9de1003ace06949dc654bc4876efe89ec53455a7721e47cd';
foreach ([
    'application/common/service/ElectronicMenu.php' => $expectedServiceHash,
    'application/common/service/ElectronicMenuDevice.php' => '3335769aee94126f7abfae2f2a305ba09cca9270df2ab7590657c00fabef855f',
    'application/p/controller/ElectronicMenu.php' => 'a93de90caced9884bb40374b9f3da7cbb04997930023e6cb229a7ca7ffefc2d7',
    'application/api/controller/ElectronicMenu.php' => '2c1df1125c5ced2abd4f97a460f4290950d8ca5fbb978d63800e76ba5d60e056',
] as $source => $expectedHash) {
    if (hash_file('sha256', $root . '/' . $source) !== $expectedHash) {
        throw new RuntimeException('Electronic menu runtime source drift');
    }
}
$cmdline = is_file('/proc/' . $pid . '/cmdline')
    ? (string)file_get_contents('/proc/' . $pid . '/cmdline') : '';
if (strpos($cmdline, '127.0.0.1:' . parse_url($base, PHP_URL_PORT)) === false
    || strpos($cmdline, $root . '/public') === false) {
    throw new RuntimeException('Isolated listener PID/docroot mismatch');
}
$singleWorker = static function (int $listenerPid): bool {
    $environment = (string)@file_get_contents('/proc/' . $listenerPid . '/environ');
    $children = (string)@file_get_contents('/proc/' . $listenerPid
        . '/task/' . $listenerPid . '/children');
    if ($environment === '' || trim($children) !== '') return false;
    if (preg_match('/(?:^|\x00)PHP_CLI_SERVER_WORKERS=(\d+)(?:\x00|$)/',
        $environment, $match) && (int)$match[1] > 1) return false;
    return true;
};
if (!$singleWorker($pid)) throw new RuntimeException('Single-worker listener not proven');
$boundary = json_decode((string)@file_get_contents($base . '/__poc_boundary'), true);
if (!is_array($boundary) || empty($boundary['external_stubs'])
    || empty($boundary['redis_isolated']) || !empty($boundary['real_queue'])) {
    throw new RuntimeException('External/Redis/queue isolation missing');
}
$runtime = (static function (string $path): array {
    $value = require $path;
    if (!is_array($value)) throw new RuntimeException('Invalid runtime config');
    return $value;
})($root . '/application/database.php');
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 config');
        return $value;
    })();
    foreach (['hostname', 'database', 'username', 'password'] as $key) {
        if (($runtime[$key] ?? null) !== ($local[$key] ?? null)) {
            throw new RuntimeException('Runtime differs from code-local MySQL');
        }
    }
    if ((int)($runtime['hostport'] ?? 3306) !== (int)($local['hostport'] ?? 3306)) {
        throw new RuntimeException('MySQL port mismatch');
    }
    $dsn = 'mysql:host=' . $runtime['hostname'] . ';port='
        . (int)($runtime['hostport'] ?? 3306) . ';dbname=' . $runtime['database']
        . ';charset=' . (string)($runtime['charset'] ?? 'utf8');
    $user = (string)$runtime['username'];
    $password = (string)$runtime['password'];
} else {
    if ((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('Wrong nonproduction DM business instance');
    }
    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('DM runtime/worker context differs');
        }
    }
    $dsn = 'dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';
    $user = (string)getenv('POC_USER');
    $password = (string)getenv('POC_PASSWORD');
}
$db = new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_TIMEOUT => 5]);
if ($dialect === 'mysql') {
    $dbIdentity = (string)$db->query("SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())")
        ->fetchColumn();
    $hostFingerprint = null;
    $dmListenerLocal = null;
} else {
    $schema = (string)$db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")
        ->fetchColumn();
    if (strtoupper($schema) !== 'ZHCT_APP') {
        throw new RuntimeException('DM connected schema differs');
    }
    $dbIdentity = 'ZHCT_APP|5237|' . $schema;
    $machineId = trim((string)@file_get_contents('/etc/machine-id'));
    if ($machineId === '' || gethostname() === false) {
        throw new RuntimeException('DM host identity unavailable');
    }
    $hostFingerprint = hash('sha256', gethostname() . '|' . $machineId);
    $listeners = [];
    $listenerExit = 0;
    @exec('/usr/sbin/ss -ltnp 2>/dev/null', $listeners, $listenerExit);
    $dmListenerLocal = false;
    if ($listenerExit === 0) {
        foreach ($listeners as $listenerLine) {
            if (preg_match('/\*:5237\s+.*users:\(\("dmserver",pid=(\d+),/',
                $listenerLine, $match)) {
                $executable = @readlink('/proc/' . $match[1] . '/exe');
                $dmListenerLocal = is_string($executable)
                    && basename($executable) === 'dmserver';
                break;
            }
        }
    }
    if (!$dmListenerLocal) throw new RuntimeException('5237 is not a local dmserver listener');
}
$dbFingerprint = hash('sha256', $dbIdentity);
if ($action !== '--preflight'
    && ((string)getenv('CDX_EBOARD_DB_SHA') !== $dbFingerprint
        || ($dialect === 'dm'
            && (string)getenv('CDX_EBOARD_HOST_SHA') !== $hostFingerprint))) {
    throw new RuntimeException('Approved database/host fingerprint mismatch');
}
$table = static function (string $name) use ($dialect): string {
    if (!preg_match('/^[a-z_]+$/', $name)) throw new RuntimeException('Invalid table');
    return $dialect === 'dm' ? strtoupper('ydy_' . $name) : 'ydy_' . $name;
};
$count = static function (string $name) use ($db, $table): int {
    return (int)$db->query('SELECT COUNT(*) FROM ' . $table($name))->fetchColumn();
};
$required = ['user', 'electronic_menu', 'electronic_menu_bind_code',
    'electronic_menu_device', 'electronic_menu_device_log',
    'restaurants', 'recipes', 'dishes', 'dishes_tag'];
$counts = [];
foreach ($required as $name) $counts[$name] = $count($name);
$menu = $db->query('SELECT ID,LEFT_RESTAURANT_ID,RIGHT_RESTAURANT_ID FROM '
    . $table('electronic_menu')
    . ' WHERE STATUS=1 AND IS_DELETE=0 AND STORE_ID=10001 ORDER BY ID')
    ->fetch(PDO::FETCH_ASSOC);
if (!$menu || (int)$menu['left_restaurant_id'] <= 0) {
    throw new RuntimeException('No existing safe restaurant fixture');
}
$dualMenu = $db->query('SELECT menu.LEFT_RESTAURANT_ID,menu.RIGHT_RESTAURANT_ID FROM '
    . $table('electronic_menu') . ' menu JOIN ' . $table('restaurants')
    . ' left_restaurant ON left_restaurant.ID=menu.LEFT_RESTAURANT_ID'
    . ' JOIN ' . $table('restaurants')
    . ' right_restaurant ON right_restaurant.ID=menu.RIGHT_RESTAURANT_ID'
    . ' WHERE menu.STATUS=1 AND menu.IS_DELETE=0 AND menu.STORE_ID=10001'
    . ' AND menu.DISPLAY_MODE=2 AND menu.RIGHT_RESTAURANT_ID>0'
    . ' AND left_restaurant.STATUS=1 AND left_restaurant.IS_DELETE=2'
    . ' AND right_restaurant.STATUS=1 AND right_restaurant.IS_DELETE=2'
    . ' ORDER BY menu.ID')->fetch(PDO::FETCH_ASSOC);
$restaurantId = $executeUpdate && $dualMenu
    ? (int)$dualMenu['left_restaurant_id'] : (int)$menu['left_restaurant_id'];
$rightRestaurantCandidate = $dualMenu
    ? (int)$dualMenu['right_restaurant_id'] : 0;
$query = $db->prepare('SELECT COUNT(*) FROM ' . $table('restaurants') . ' WHERE ID=?');
$query->execute([$restaurantId]);
if ((int)$query->fetchColumn() !== 1) throw new RuntimeException('Restaurant missing');
$rightRestaurantActive = false;
if ($dualMenu && $rightRestaurantCandidate > 0
    && $rightRestaurantCandidate !== (int)$dualMenu['left_restaurant_id']) {
    $rightQuery = $db->prepare('SELECT COUNT(*) FROM '
        . $table('restaurants')
        . ' WHERE ID IN (?,?) AND IS_DELETE=2 AND STATUS=1');
    $rightQuery->execute([(int)$dualMenu['left_restaurant_id'],
        $rightRestaurantCandidate]);
    $rightRestaurantActive = (int)$rightQuery->fetchColumn() === 2;
}
$markerRows = (int)$db->query('SELECT COUNT(*) FROM ' . $table('user')
    . " WHERE ACCOUNT LIKE 'CDXEM%'")->fetchColumn();
if ($action === '--preflight') {
    echo json_encode(['lane' => $lane, 'mode' => 'select-only-preflight',
        'runtime_isolated' => true,
        'db_target' => $dialect === 'dm' ? 'nonprod-dm-store' : 'code-local-dev-mysql',
        'table_counts' => $counts, 'candidate_restaurant_present' => true,
        'same_store_second_restaurant_active' => $rightRestaurantActive,
        'existing_synthetic_operator_rows' => $markerRows,
        'database_fingerprint' => $dbFingerprint,
        'host_fingerprint' => $hostFingerprint,
        'dm_listener_local' => $dmListenerLocal], JSON_UNESCAPED_SLASHES) . PHP_EOL;
    exit(0);
}

// Only a new synthetic operator and menu may be written. Never reuse a real menu.
if ($markerRows !== 0) throw new RuntimeException('Old synthetic operator requires review');
if ($executeUpdate && !$rightRestaurantActive) {
    throw new RuntimeException('Same-store second restaurant unavailable');
}
$restaurantQuery = $db->prepare('SELECT COUNT(*) FROM ' . $table('restaurants')
    . ' WHERE ID=? AND IS_DELETE=2');
$restaurantQuery->execute([$restaurantId]);
if ((int)$restaurantQuery->fetchColumn() !== 1) {
    throw new RuntimeException('Selected restaurant is not active');
}
$db->query('SELECT ID,UUID,ACCOUNT,PWD,SALT,NAME,TYPE,CREATE_TIME,CREATE_BY,IS_DELETE'
    . ' FROM ' . $table('user') . ' WHERE 1=0');
$db->query('SELECT ID,UUID,PUBLIC_TOKEN,CREATE_BY,LEFT_RESTAURANT_ID'
    . ' FROM ' . $table('electronic_menu') . ' WHERE 1=0');
if ($executeDevice || $executeExpired) {
    $db->query('SELECT ID,MENU_ID,CODE_HASH,USED_AT,STATUS,CREATE_BY'
        . ' FROM ' . $table('electronic_menu_bind_code') . ' WHERE 1=0');
    $db->query('SELECT ID,UUID,DEVICE_ID,DEVICE_TOKEN_HASH,MENU_ID,STATUS,'
        . ' LAST_SEEN_TIME,CREATE_BY FROM ' . $table('electronic_menu_device')
        . ' WHERE 1=0');
    $db->query('SELECT ID,UUID,DEVICE_RECORD_ID,MENU_ID,LEVEL,EVENT_CODE,'
        . ' CONTEXT_JSON,CREATE_BY FROM ' . $table('electronic_menu_device_log')
        . ' WHERE 1=0');
}
$connect = static function () use ($dsn, $user, $password): PDO {
    return new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_TIMEOUT => 5]);
};
$menuSourceSql = 'SELECT * FROM ' . $table('electronic_menu') . ' ORDER BY ID';
$sourceBefore = [];
foreach (['electronic_menu', 'electronic_menu_bind_code',
    'electronic_menu_device', 'electronic_menu_device_log'] as $sourceName) {
    $sourceBefore[$sourceName] = hash('sha256', serialize($db->query('SELECT * FROM '
        . $table($sourceName) . ' ORDER BY ID')->fetchAll(PDO::FETCH_ASSOC)));
}
$menuBefore = $sourceBefore['electronic_menu'];
$marker = 'CDXEM' . strtoupper(bin2hex(random_bytes(8)));
$operatorId = 0;
$menuId = 0;
$copyId = 0;
$menuUuid = '';
$publicToken = '';
$bindCode = '';
$deviceToken = '';
$deviceRecordId = 0;
$results = [];
$failure = '';
$cleanup = [];
$assert = static function (bool $condition, string $message): void {
    if (!$condition) throw new RuntimeException($message);
};
$post = static function (string $path, array $form, string $token = '') use ($base): array {
    $headers = "Content-Type: application/x-www-form-urlencoded\r\n";
    if ($token !== '') $headers .= 'token: ' . $token . "\r\n";
    $context = stream_context_create(['http' => [
        'method' => 'POST', 'header' => $headers,
        'content' => http_build_query($form, '', '&', PHP_QUERY_RFC3986),
        'timeout' => 30, 'ignore_errors' => true,
    ]]);
    $body = @file_get_contents($base . $path, false, $context);
    $headers = $http_response_header ?? [];
    preg_match('/HTTP\/\S+\s+(\d+)/', (string)($headers[0] ?? ''), $match);
    $json = is_string($body) ? json_decode($body, true) : null;
    return ['http' => isset($match[1]) ? (int)$match[1] : 0,
        'json' => is_array($json) ? $json : null];
};
$get = static function (string $path) use ($base): array {
    $context = stream_context_create(['http' => [
        'method' => 'GET', 'timeout' => 30, 'ignore_errors' => true,
    ]]);
    $body = @file_get_contents($base . $path, false, $context);
    $headers = $http_response_header ?? [];
    preg_match('/HTTP\/\S+\s+(\d+)/', (string)($headers[0] ?? ''), $match);
    $json = is_string($body) ? json_decode($body, true) : null;
    return ['http' => isset($match[1]) ? (int)$match[1] : 0,
        'json' => is_array($json) ? $json : null];
};
$success = static function (array $response): bool {
    return $response['http'] === 200 && is_array($response['json'])
        && ($response['json']['code'] ?? null) === 0;
};
$payloadSummary = static function (array $data) use ($db, $table, $restaurantId): array {
    $config = $data['config'] ?? null;
    $context = $data['context'] ?? null;
    $stalls = $data['stalls'] ?? null;
    if (!is_array($config) || !is_array($context) || !is_array($stalls)
        || count($stalls) !== 1 || (int)($config['display_mode'] ?? 0) !== 1
        || (int)($config['carousel_interval'] ?? 0) !== 8
        || !preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($context['business_date'] ?? ''))
        || !isset($context['meal_times']) || !is_int($context['meal_times'])
        || (int)($stalls[0]['restaurant_id'] ?? 0) !== $restaurantId
        || ($stalls[0]['position'] ?? null) !== 'left'
        || !is_array($stalls[0]['dishes'] ?? null)) {
        throw new RuntimeException('Electronic menu payload shape mismatch');
    }
    $dishes = $stalls[0]['dishes'];
    $source = $db->prepare('SELECT COUNT(*) FROM ' . $table('recipes') . ' recipes'
        . ' JOIN ' . $table('dishes') . ' d ON d.UUID=recipes.DISHES_UUID'
        . ' WHERE recipes.RESTAURANT_ID=? AND recipes.MENU_DATE=?'
        . ' AND recipes.MEAL_TIMES=? AND d.STATUS=1 AND d.IS_DEL=1');
    $source->execute([$restaurantId, $context['business_date'], $context['meal_times']]);
    if (count($dishes) !== (int)$source->fetchColumn()) {
        throw new RuntimeException('Electronic menu dish count differs from source JOIN');
    }
    foreach ($dishes as $dish) {
        if (!is_array($dish) || !isset($dish['uuid'], $dish['name'], $dish['image_url'])
            || !is_array($dish['health_tags'] ?? null)) {
            throw new RuntimeException('Dish fields missing');
        }
        foreach (['price', 'carbohydrate', 'protein', 'fat'] as $field) {
            if (!isset($dish[$field]) || !is_string($dish[$field])
                || !preg_match('/^-?\d+\.\d{2}$/', $dish[$field])) {
                throw new RuntimeException('Dish fixed-decimal response type mismatch');
            }
        }
    }
    $types = $dishes ? array_map('gettype', $dishes[0]) : [];
    ksort($types);
    return ['dish_count' => count($dishes), 'source_count_match' => true,
        'dish_key_types' => $types];
};
try {
    $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table('user')
        . ' WHERE UUID=? OR ACCOUNT=?');
    $stmt->execute([$marker, $marker]);
    $assert((int)$stmt->fetchColumn() === 0, 'Operator marker collision');
    $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table('electronic_menu')
        . ' WHERE CREATE_BY=?');
    $stmt->execute([$marker]);
    $assert((int)$stmt->fetchColumn() === 0, 'Menu marker collision');

    $stmt = $db->prepare('INSERT INTO ' . $table('user')
        . ' (UUID,ACCOUNT,PWD,SALT,NAME,TYPE,CREATE_TIME,CREATE_BY,IS_DELETE)'
        . ' VALUES (?,?,?,?,?,?,?,?,?)');
    $stmt->execute([$marker, $marker, 'DISABLED', strtoupper(bin2hex(random_bytes(8))),
        $marker, 0, date('Y-m-d H:i:s'), 'CODEX', 0]);
    $stmt = $db->prepare('SELECT ID FROM ' . $table('user')
        . ' WHERE UUID=? AND ACCOUNT=? AND TYPE=0 AND CREATE_BY=?');
    $stmt->execute([$marker, $marker, 'CODEX']);
    $actor = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
    $operatorId = (int)($actor['id'] ?? 0);
    $assert($operatorId > 0, 'Synthetic operator insert/readback failed');
    require_once $root . '/application/base/Security.php';
    $token = \app\base\Security::encrypt(implode("\t",
        [(string)$operatorId, $marker, $marker, '0', '', '', $marker]));
    $assert(is_string($token) && $token !== '', 'Synthetic token unavailable');

    $config = ['display_mode' => 1, 'left_restaurant_id' => $restaurantId,
        'carousel_interval' => 8];
    $preview = $post('/p/electronicMenu/previewData', $config, $token);
    $previewData = $preview['json']['data'] ?? null;
    $assert($success($preview) && is_array($previewData), 'Preview HTTP failed');
    $results['preview_positive'] = $payloadSummary($previewData);

    $invalid = $post('/p/electronicMenu/save',
        array_merge($config, ['carousel_interval' => 2]), $token);
    $assert($invalid['http'] === 200 && ($invalid['json']['code'] ?? null) === 1,
        'Invalid carousel interval not rejected');
    $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table('electronic_menu')
        . ' WHERE CREATE_BY=?');
    $stmt->execute([$marker]);
    $assert((int)$stmt->fetchColumn() === 0, 'Invalid save unexpectedly wrote menu');
    $results['invalid_save_rejected'] = true;

    $save = $post('/p/electronicMenu/save', $config + ['id' => 0], $token);
    $saveData = $save['json']['data'] ?? null;
    $assert($success($save) && is_array($saveData), 'Save HTTP/contract failed');
    $menuId = (int)($saveData['id'] ?? 0);
    $menuUuid = (string)($saveData['uuid'] ?? '');
    $publicToken = (string)($saveData['public_token'] ?? '');
    $assert($menuId > 0 && $menuUuid !== ''
        && preg_match('/^[a-f0-9]{64}$/', $publicToken) === 1,
        'Saved menu ID/UUID/token invalid');
    $stmt = $db->prepare('SELECT ID,UUID,PUBLIC_TOKEN,CREATE_BY,LEFT_RESTAURANT_ID,'
        . ' RIGHT_RESTAURANT_ID,DISPLAY_MODE,CAROUSEL_INTERVAL,STORE_ID,STATUS,IS_DELETE'
        . ' FROM ' . $table('electronic_menu') . ' WHERE ID=?');
    $stmt->execute([$menuId]);
    $owned = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
    $assert((int)($owned['id'] ?? 0) === $menuId
        && (string)($owned['uuid'] ?? '') === $menuUuid
        && (string)($owned['public_token'] ?? '') === $publicToken
        && (string)($owned['create_by'] ?? '') === $marker
        && (int)($owned['left_restaurant_id'] ?? 0) === $restaurantId
        && (int)($owned['right_restaurant_id'] ?? -1) === 0
        && (int)($owned['display_mode'] ?? 0) === 1
        && (int)($owned['carousel_interval'] ?? 0) === 8
        && (int)($owned['store_id'] ?? 0) === 10001
        && (int)($owned['status'] ?? 0) === 1
        && (int)($owned['is_delete'] ?? -1) === 0,
        'Saved menu source readback mismatch');
    $results['save_source_readback'] = true;

    $detail = $post('/p/electronicMenu/detail', ['id' => $menuId], $token);
    $assert($success($detail)
        && (int)($detail['json']['data']['id'] ?? 0) === $menuId
        && (string)($detail['json']['data']['public_token'] ?? '') === $publicToken,
        'Detail contract failed');
    $results['detail_source_match'] = true;

    $list = $post('/p/electronicMenu/list', ['page' => 1, 'pageSize' => 10], $token);
    $listed = false;
    foreach (($list['json']['data']['rows'] ?? []) as $item) {
        if ((int)($item['id'] ?? 0) === $menuId
            && (string)($item['public_token'] ?? '') === $publicToken) $listed = true;
    }
    $assert($success($list) && $listed, 'List does not include synthetic menu');
    $results['list_includes_owned_menu'] = true;

    $play = $get('/api/electronicMenu/play/' . $publicToken);
    $playData = $play['json']['data'] ?? null;
    $assert($success($play) && is_array($playData), 'Synthetic menu play failed');
    $results['play_positive'] = $payloadSummary($playData);

    if ($executeExpired) {
        $binding = $post('/p/electronicMenu/createBindCode',
            ['id' => $menuId], $token);
        $bindData = $binding['json']['data'] ?? null;
        $bindCode = is_array($bindData) ? (string)($bindData['bind_code'] ?? '') : '';
        $assert($success($binding) && preg_match('/^\d{6}$/', $bindCode) === 1
            && (int)($bindData['menu_id'] ?? 0) === $menuId,
            'Synthetic expiring bind code unavailable');
        $bindHash = hash('sha256', $bindCode);
        $stmt = $db->prepare('SELECT ID,STATUS,USED_AT FROM '
            . $table('electronic_menu_bind_code')
            . ' WHERE MENU_ID=? AND CODE_HASH=? AND CREATE_BY=?');
        $stmt->execute([$menuId, $bindHash, $marker]);
        $bindRow = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $bindId = (int)($bindRow['id'] ?? 0);
        $assert($bindId > 0 && (int)($bindRow['status'] ?? 0) === 1
            && ($bindRow['used_at'] ?? null) === null,
            'Synthetic bind code source row mismatch');

        $expiredAt = date('Y-m-d H:i:s', time() - 60);
        $stmt = $db->prepare('UPDATE ' . $table('electronic_menu_bind_code')
            . ' SET EXPIRES_AT=? WHERE ID=? AND MENU_ID=?'
            . ' AND CODE_HASH=? AND CREATE_BY=? AND STATUS=1');
        $stmt->execute([$expiredAt, $bindId, $menuId, $bindHash, $marker]);
        $stmt = $db->prepare('SELECT STATUS,USED_AT,EXPIRES_AT FROM '
            . $table('electronic_menu_bind_code') . ' WHERE ID=?');
        $stmt->execute([$bindId]);
        $expiredRow = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $assert((int)($expiredRow['status'] ?? 0) === 1
            && ($expiredRow['used_at'] ?? null) === null
            && substr((string)($expiredRow['expires_at'] ?? ''), 0, 19) === $expiredAt,
            'Synthetic bind code expiry source mismatch');
        $results['expired_code_fixture_exact_row'] = true;

        $deviceId = $marker . 'E';
        $stmt = $db->prepare('SELECT COUNT(*) FROM '
            . $table('electronic_menu_device') . ' WHERE DEVICE_ID=?');
        $stmt->execute([$deviceId]);
        $assert((int)$stmt->fetchColumn() === 0,
            'Synthetic expiring device ID collision');
        $beforeExpiryAttempt = $db->query('SELECT * FROM '
            . $table('electronic_menu_bind_code') . ' WHERE ID=' . $bindId)
            ->fetch(PDO::FETCH_ASSOC);
        $activation = $post('/api/electronicMenu/device/activate',
            ['bind_code' => $bindCode, 'device_id' => $deviceId,
                'device_name' => $marker]);
        $afterExpiryAttempt = $db->query('SELECT * FROM '
            . $table('electronic_menu_bind_code') . ' WHERE ID=' . $bindId)
            ->fetch(PDO::FETCH_ASSOC);
        $stmt = $db->prepare('SELECT COUNT(*) FROM '
            . $table('electronic_menu_device') . ' WHERE DEVICE_ID=?');
        $stmt->execute([$deviceId]);
        $assert($activation['http'] === 200
            && ($activation['json']['code'] ?? null) === 1
            && ($activation['json']['message'] ?? null) === '绑定码无效或已过期'
            && ($activation['json']['data'] ?? null) === []
            && serialize($beforeExpiryAttempt) === serialize($afterExpiryAttempt)
            && (int)$stmt->fetchColumn() === 0,
            'Expired code accepted or mutated source/device');
        $results['expired_activation_rejected_zero_device_write'] = true;
        $bindCode = '';
    }

    if ($executeUpdate) {
        $rightRestaurantId = $rightRestaurantCandidate;
        $assert($rightRestaurantId > 0 && $rightRestaurantId !== $restaurantId
            && $rightRestaurantActive,
            'No second active restaurant from same-store existing menu');
        $dualConfig = ['id' => $menuId, 'display_mode' => 2,
            'left_restaurant_id' => $restaurantId,
            'right_restaurant_id' => $rightRestaurantId,
            'carousel_interval' => 9];
        $dualSummary = static function (array $data) use ($db, $table,
            $restaurantId, $rightRestaurantId): array {
            if ((int)($data['config']['display_mode'] ?? 0) !== 2
                || (int)($data['config']['carousel_interval'] ?? 0) !== 9
                || !preg_match('/^\d{4}-\d{2}-\d{2}$/',
                    (string)($data['context']['business_date'] ?? ''))
                || !is_int($data['context']['meal_times'] ?? null)
                || count($data['stalls'] ?? []) !== 2) {
                throw new RuntimeException('Dual display config/stall count mismatch');
            }
            $counts = [];
            foreach ([$restaurantId, $rightRestaurantId] as $index => $expectedId) {
                $stall = $data['stalls'][$index];
                if ((int)($stall['restaurant_id'] ?? 0) !== $expectedId
                    || ($stall['position'] ?? null) !== ($index === 0 ? 'left' : 'right')
                    || !is_array($stall['dishes'] ?? null)) {
                    throw new RuntimeException('Dual display restaurant/position mismatch');
                }
                $stmt = $db->prepare('SELECT d.UUID,d.PRICE,d.CARBOHYDRATE,'
                    . ' d.PROTEIN,d.FAT FROM ' . $table('recipes')
                    . ' recipes JOIN ' . $table('dishes')
                    . ' d ON d.UUID=recipes.DISHES_UUID'
                    . ' WHERE recipes.RESTAURANT_ID=? AND recipes.MENU_DATE=?'
                    . ' AND recipes.MEAL_TIMES=? AND d.STATUS=1 AND d.IS_DEL=1'
                    . ' ORDER BY recipes.ID');
                $stmt->execute([$expectedId, $data['context']['business_date'],
                    (int)$data['context']['meal_times']]);
                $sourceDishes = $stmt->fetchAll(PDO::FETCH_ASSOC);
                if (count($stall['dishes']) !== count($sourceDishes)) {
                    throw new RuntimeException('Dual display dish count/source mismatch');
                }
                foreach ($stall['dishes'] as $dishIndex => $dish) {
                    $sourceDish = $sourceDishes[$dishIndex];
                    if (!is_array($dish)
                        || !isset($dish['uuid'], $dish['name'], $dish['image_url'])
                        || !is_string($dish['name'])
                        || !is_string($dish['image_url'])
                        || !array_key_exists('spicy_level', $dish)
                        || !is_array($dish['health_tags'] ?? null)
                        || strtoupper(trim((string)$dish['uuid']))
                            !== strtoupper(trim((string)$sourceDish['uuid']))) {
                        throw new RuntimeException('Dual display dish identity/keys mismatch');
                    }
                    foreach (['price', 'carbohydrate', 'protein', 'fat'] as $field) {
                        if (!isset($dish[$field]) || !is_string($dish[$field])
                            || !preg_match('/^-?\d+\.\d{2}$/', $dish[$field])
                            || $dish[$field] !== number_format(
                                (float)($sourceDish[$field] ?? 0), 2, '.', '')) {
                            throw new RuntimeException('Dual display decimal type mismatch');
                        }
                    }
                }
                $counts[] = count($stall['dishes']);
            }
            return ['stall_count' => 2, 'dish_counts' => $counts,
                'source_counts_match' => true, 'numeric_strings' => true];
        };
        $dualPreview = $post('/p/electronicMenu/previewData', $dualConfig, $token);
        $assert($success($dualPreview)
            && is_array($dualPreview['json']['data'] ?? null),
            'Dual preview HTTP failed');
        $results['dual_preview_positive'] = $dualSummary($dualPreview['json']['data']);

        $updated = $post('/p/electronicMenu/save', $dualConfig, $token);
        $updateData = $updated['json']['data'] ?? null;
        $assert($success($updated) && is_array($updateData)
            && (int)($updateData['id'] ?? 0) === $menuId
            && (string)($updateData['uuid'] ?? '') === $menuUuid
            && (string)($updateData['public_token'] ?? '') === $publicToken,
            'Dual update changed menu identity/HTTP failed');
        $stmt = $db->prepare('SELECT DISPLAY_MODE,LEFT_RESTAURANT_ID,'
            . ' RIGHT_RESTAURANT_ID,CAROUSEL_INTERVAL,UUID,PUBLIC_TOKEN,'
            . ' STORE_ID,CREATE_BY FROM '
            . $table('electronic_menu') . ' WHERE ID=? AND UUID=?');
        $stmt->execute([$menuId, $menuUuid]);
        $updatedRow = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $assert((int)($updatedRow['display_mode'] ?? 0) === 2
            && (int)($updatedRow['left_restaurant_id'] ?? 0) === $restaurantId
            && (int)($updatedRow['right_restaurant_id'] ?? 0) === $rightRestaurantId
            && (int)($updatedRow['carousel_interval'] ?? 0) === 9
            && (string)($updatedRow['uuid'] ?? '') === $menuUuid
            && (string)($updatedRow['public_token'] ?? '') === $publicToken
            && (int)($updatedRow['store_id'] ?? 0) === 10001
            && (string)($updatedRow['create_by'] ?? '') === $marker,
            'Dual update input not stored');
        $dualPlay = $get('/api/electronicMenu/play/' . $publicToken);
        $assert($success($dualPlay) && is_array($dualPlay['json']['data'] ?? null),
            'Dual updated menu not playable');
        $results['dual_update_and_play'] = $dualSummary($dualPlay['json']['data']);

        $rowBeforeInvalid = $db->query('SELECT * FROM '
            . $table('electronic_menu') . ' WHERE ID=' . $menuId)
            ->fetch(PDO::FETCH_ASSOC);
        $badDual = $post('/p/electronicMenu/save',
            array_merge($dualConfig, ['right_restaurant_id' => $restaurantId]),
            $token);
        $rowAfterInvalid = $db->query('SELECT * FROM '
            . $table('electronic_menu') . ' WHERE ID=' . $menuId)
            ->fetch(PDO::FETCH_ASSOC);
        $assert($badDual['http'] === 200 && ($badDual['json']['code'] ?? null) === 1
            && serialize($rowBeforeInvalid) === serialize($rowAfterInvalid),
            'Invalid same-restaurant dual update wrote data');
        $results['invalid_dual_update_zero_write'] = true;

        $restore = $post('/p/electronicMenu/save',
            ['id' => $menuId, 'display_mode' => 1,
                'left_restaurant_id' => $restaurantId,
                'right_restaurant_id' => 0, 'carousel_interval' => 8], $token);
        $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table('electronic_menu')
            . ' WHERE CREATE_BY=?');
        $stmt->execute([$marker]);
        $ownedCount = (int)$stmt->fetchColumn();
        $stmt = $db->prepare('SELECT DISPLAY_MODE,RIGHT_RESTAURANT_ID,'
            . ' CAROUSEL_INTERVAL,UUID,PUBLIC_TOKEN,STORE_ID,CREATE_BY FROM '
            . $table('electronic_menu')
            . ' WHERE ID=?');
        $stmt->execute([$menuId]);
        $restoredRow = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $assert($success($restore) && $ownedCount === 1
            && (int)($restoredRow['display_mode'] ?? 0) === 1
            && (int)($restoredRow['right_restaurant_id'] ?? -1) === 0
            && (int)($restoredRow['carousel_interval'] ?? 0) === 8
            && (string)($restoredRow['uuid'] ?? '') === $menuUuid
            && (string)($restoredRow['public_token'] ?? '') === $publicToken
            && (int)($restoredRow['store_id'] ?? 0) === 10001
            && (string)($restoredRow['create_by'] ?? '') === $marker,
            'Single display restore inserted row or changed token');
        $restoredPlay = $get('/api/electronicMenu/play/' . $publicToken);
        $assert($success($restoredPlay)
            && is_array($restoredPlay['json']['data'] ?? null),
            'Restored single display not playable');
        $results['single_restore_same_id_token']
            = $payloadSummary($restoredPlay['json']['data']);
    }

    if ($executeCopy) {
        $originalBeforeCopy = $db->query('SELECT * FROM '
            . $table('electronic_menu') . ' WHERE ID=' . $menuId)
            ->fetch(PDO::FETCH_ASSOC);
        $copy = $post('/p/electronicMenu/copy', ['id' => $menuId], $token);
        $copyData = $copy['json']['data'] ?? null;
        $copyId = is_array($copyData) ? (int)($copyData['id'] ?? 0) : 0;
        $copyToken = is_array($copyData) ? (string)($copyData['public_token'] ?? '') : '';
        $assert($success($copy) && $copyId > 0 && $copyId !== $menuId
            && preg_match('/^[a-f0-9]{64}$/', $copyToken) === 1
            && $copyToken !== $publicToken
            && (int)($copyData['left_restaurant_id'] ?? 0) === $restaurantId
            && (int)($copyData['display_mode'] ?? 0) === 1
            && (int)($copyData['carousel_interval'] ?? 0) === 8,
            'Copy HTTP/new ID/token/config contract failed');
        $stmt = $db->prepare('SELECT ID,UUID,PUBLIC_TOKEN,CREATE_BY,STORE_ID'
            . ' FROM ' . $table('electronic_menu') . ' WHERE ID=?');
        $stmt->execute([$copyId]);
        $copyRow = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $originalAfterCopy = $db->query('SELECT * FROM '
            . $table('electronic_menu') . ' WHERE ID=' . $menuId)
            ->fetch(PDO::FETCH_ASSOC);
        $assert((int)($copyRow['id'] ?? 0) === $copyId
            && (string)($copyRow['uuid'] ?? '') !== ''
            && (string)($copyRow['uuid'] ?? '') !== $menuUuid
            && (string)($copyRow['public_token'] ?? '') === $copyToken
            && (string)($copyRow['create_by'] ?? '') === $marker
            && (int)($copyRow['store_id'] ?? 0) === 10001
            && serialize($originalBeforeCopy) === serialize($originalAfterCopy),
            'Copy source/original immutability readback failed');
        $copyPlay = $get('/api/electronicMenu/play/' . $copyToken);
        $copyPlayData = $copyPlay['json']['data'] ?? null;
        $assert($success($copyPlay) && is_array($copyPlayData),
            'Copied menu not playable');
        $results['copy_new_menu_source_and_play'] = $payloadSummary($copyPlayData);
        $copyRowsBeforeInvalid = $db->query('SELECT * FROM '
            . $table('electronic_menu') . ' WHERE CREATE_BY=' . $db->quote($marker)
            . ' ORDER BY ID')->fetchAll(PDO::FETCH_ASSOC);
        $badCopy = $post('/p/electronicMenu/copy', ['id' => 0], $token);
        $copyRowsAfterInvalid = $db->query('SELECT * FROM '
            . $table('electronic_menu') . ' WHERE CREATE_BY=' . $db->quote($marker)
            . ' ORDER BY ID')->fetchAll(PDO::FETCH_ASSOC);
        $assert($badCopy['http'] === 200 && ($badCopy['json']['code'] ?? null) === 1
            && count($copyRowsBeforeInvalid) === 2
            && serialize($copyRowsBeforeInvalid) === serialize($copyRowsAfterInvalid),
            'Invalid copy not rejected without write');
        $results['invalid_copy_rejected_zero_write'] = true;
    }

    if ($executeDevice) {
        $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table('electronic_menu_device')
            . ' WHERE DEVICE_ID IN (?,?)');
        $stmt->execute([$marker, $marker . 'R']);
        $assert((int)$stmt->fetchColumn() === 0, 'Synthetic device ID collision');

        $binding = $post('/p/electronicMenu/createBindCode', ['id' => $menuId], $token);
        $bindData = $binding['json']['data'] ?? null;
        $bindCode = is_array($bindData) ? (string)($bindData['bind_code'] ?? '') : '';
        $assert($success($binding) && preg_match('/^\d{6}$/', $bindCode) === 1
            && (int)($bindData['menu_id'] ?? 0) === $menuId
            && (int)($bindData['expires_in'] ?? 0) === 600,
            'Binding code HTTP/contract failed');
        $stmt = $db->prepare('SELECT ID,STATUS,USED_AT FROM '
            . $table('electronic_menu_bind_code')
            . ' WHERE MENU_ID=? AND CODE_HASH=? AND CREATE_BY=?');
        $stmt->execute([$menuId, hash('sha256', $bindCode), $marker]);
        $bindRow = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $assert((int)($bindRow['id'] ?? 0) > 0 && (int)($bindRow['status'] ?? 0) === 1
            && ($bindRow['used_at'] ?? null) === null,
            'Binding code source row mismatch');
        $results['create_bind_code_source_readback'] = true;

        $activation = $post('/api/electronicMenu/device/activate',
            ['bind_code' => $bindCode, 'device_id' => $marker,
                'device_name' => $marker]);
        $activationData = $activation['json']['data'] ?? null;
        $deviceToken = is_array($activationData)
            ? (string)($activationData['device_token'] ?? '') : '';
        $assert($success($activation) && preg_match('/^[a-f0-9]{64}$/', $deviceToken) === 1
            && (int)($activationData['menu_id'] ?? 0) === $menuId
            && (string)($activationData['device_id'] ?? '') === $marker
            && strpos((string)($activationData['public_path'] ?? ''), $publicToken) !== false
            && preg_match('/^[a-f0-9]{64}$/',
                (string)($activationData['config_version'] ?? '')) === 1,
            'Device activation HTTP/contract failed');
        $stmt = $db->prepare('SELECT ID,UUID,DEVICE_TOKEN_HASH,MENU_ID,STATUS,'
            . ' LAST_SEEN_TIME FROM ' . $table('electronic_menu_device')
            . ' WHERE STORE_ID=10001 AND DEVICE_ID=?');
        $stmt->execute([$marker]);
        $deviceRow = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $deviceRecordId = (int)($deviceRow['id'] ?? 0);
        $assert($deviceRecordId > 0 && (string)($deviceRow['uuid'] ?? '') !== ''
            && (string)($deviceRow['device_token_hash'] ?? '') === hash('sha256', $deviceToken)
            && (int)($deviceRow['menu_id'] ?? 0) === $menuId
            && (int)($deviceRow['status'] ?? 0) === 1
            && !empty($deviceRow['last_seen_time']),
            'Device activation source row mismatch');
        $stmt = $db->prepare('SELECT STATUS,USED_AT FROM '
            . $table('electronic_menu_bind_code') . ' WHERE ID=?');
        $stmt->execute([(int)$bindRow['id']]);
        $usedCode = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        $assert((int)($usedCode['status'] ?? 0) === 2
            && !empty($usedCode['used_at']), 'Binding code not consumed once');
        $results['activate_device_source_readback'] = true;

        $beforeReplayCode = $db->query('SELECT * FROM '
            . $table('electronic_menu_bind_code') . ' WHERE ID=' . (int)$bindRow['id'])
            ->fetch(PDO::FETCH_ASSOC);
        $beforeReplayDevice = $db->query('SELECT * FROM '
            . $table('electronic_menu_device') . ' WHERE ID=' . $deviceRecordId)
            ->fetch(PDO::FETCH_ASSOC);
        $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table('electronic_menu_device_log')
            . ' WHERE MENU_ID=?');
        $stmt->execute([$menuId]);
        $beforeReplayLogCount = (int)$stmt->fetchColumn();
        $retry = $post('/api/electronicMenu/device/activate',
            ['bind_code' => $bindCode, 'device_id' => $marker . 'R',
                'device_name' => $marker]);
        $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table('electronic_menu_device')
            . ' WHERE DEVICE_ID=?');
        $stmt->execute([$marker . 'R']);
        $replayDeviceCount = (int)$stmt->fetchColumn();
        $afterReplayCode = $db->query('SELECT * FROM '
            . $table('electronic_menu_bind_code') . ' WHERE ID=' . (int)$bindRow['id'])
            ->fetch(PDO::FETCH_ASSOC);
        $afterReplayDevice = $db->query('SELECT * FROM '
            . $table('electronic_menu_device') . ' WHERE ID=' . $deviceRecordId)
            ->fetch(PDO::FETCH_ASSOC);
        $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table('electronic_menu_device_log')
            . ' WHERE MENU_ID=?');
        $stmt->execute([$menuId]);
        $assert($retry['http'] === 200 && ($retry['json']['code'] ?? null) === 1
            && $replayDeviceCount === 0
            && serialize($beforeReplayCode) === serialize($afterReplayCode)
            && serialize($beforeReplayDevice) === serialize($afterReplayDevice)
            && (int)$stmt->fetchColumn() === $beforeReplayLogCount,
            'Consumed binding code replay not rejected without write');
        $results['bind_code_replay_rejected_zero_write'] = true;

        $configResponse = $post('/api/electronicMenu/device/config',
            ['device_id' => $marker, 'device_token' => $deviceToken]);
        $configData = $configResponse['json']['data'] ?? null;
        $assert($success($configResponse) && is_array($configData)
            && !array_key_exists('device_token', $configData)
            && (int)($configData['menu_id'] ?? 0) === $menuId
            && (string)($configData['config_version'] ?? '')
                === (string)$activationData['config_version'],
            'Device config contract failed');
        $results['device_config_positive'] = true;

        $devices = $post('/p/electronicMenu/devices', ['id' => $menuId], $token);
        $deviceListed = false;
        foreach (($devices['json']['data'] ?? []) as $item) {
            if ((int)($item['id'] ?? 0) === $deviceRecordId
                && (string)($item['device_id'] ?? '') === $marker) $deviceListed = true;
        }
        $assert($success($devices) && $deviceListed,
            'PC device list missing synthetic device');
        $results['pc_devices_includes_owned_device'] = true;

        $logPayload = [['level' => 'info', 'event_code' => 'CDXEM.TEST',
            'error_code' => 'CDXEM.OK', 'message' => $marker,
            'context' => ['android_version' => 'test', 'unsafe_key' => 'ignored']]];
        $logWrite = $post('/api/electronicMenu/device/logs',
            ['device_id' => $marker, 'device_token' => $deviceToken,
                'logs' => json_encode($logPayload, JSON_UNESCAPED_UNICODE)]);
        $assert($success($logWrite)
            && (int)($logWrite['json']['data']['accepted'] ?? 0) === 1,
            'Device log write HTTP/contract failed');
        $stmt = $db->prepare('SELECT ID,UUID,LEVEL,EVENT_CODE,ERROR_CODE,'
            . ' CONTEXT_JSON FROM ' . $table('electronic_menu_device_log')
            . ' WHERE DEVICE_RECORD_ID=? AND MENU_ID=?');
        $stmt->execute([$deviceRecordId, $menuId]);
        $logRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $logContext = count($logRows) === 1
            ? json_decode((string)$logRows[0]['context_json'], true) : null;
        $assert(count($logRows) === 1 && (int)$logRows[0]['id'] > 0
            && (string)$logRows[0]['uuid'] !== ''
            && (string)$logRows[0]['level'] === 'info'
            && (string)$logRows[0]['event_code'] === 'CDXEM.TEST'
            && (string)$logRows[0]['error_code'] === 'CDXEM.OK'
            && is_array($logContext) && isset($logContext['android_version'])
            && !isset($logContext['unsafe_key']),
            'Device log source/allowlist mismatch');
        $results['device_log_one_row_and_context_allowlist'] = true;

        $logList = $post('/p/electronicMenu/deviceLogs',
            ['device_record_id' => $deviceRecordId, 'limit' => 50], $token);
        $listedLog = false;
        foreach (($logList['json']['data'] ?? []) as $item) {
            if ((int)($item['id'] ?? 0) === (int)$logRows[0]['id']) $listedLog = true;
        }
        $assert($success($logList) && $listedLog,
            'PC device log list missing synthetic row');
        $results['pc_device_logs_includes_owned_log'] = true;

        $unbind = $post('/p/electronicMenu/unbindDevice',
            ['device_record_id' => $deviceRecordId], $token);
        $stmt = $db->prepare('SELECT STATUS FROM ' . $table('electronic_menu_device')
            . ' WHERE ID=? AND DEVICE_ID=?');
        $stmt->execute([$deviceRecordId, $marker]);
        $assert($success($unbind) && (int)$stmt->fetchColumn() === 2,
            'Unbind source status mismatch');
        $afterUnbind = $post('/api/electronicMenu/device/config',
            ['device_id' => $marker, 'device_token' => $deviceToken]);
        $assert($afterUnbind['http'] === 200
            && ($afterUnbind['json']['code'] ?? null) === 1,
            'Unbound device credentials still accepted');
        $results['unbind_revokes_device_config'] = true;
        $bindCode = '';
        $deviceToken = '';
    }
    $token = '';
} catch (Throwable $e) {
    $failure = get_class($e) . ':' . hash('sha256', $e->getMessage());
} finally {
    // Same single-worker loopback port acts as a barrier before cleanup.
    $barrier = json_decode((string)@file_get_contents($base . '/__poc_boundary'), true);
    $currentCmdline = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
    $barrierSafe = is_array($barrier) && !empty($barrier['external_stubs'])
        && !empty($barrier['redis_isolated']) && empty($barrier['real_queue'])
        && strpos($currentCmdline, '127.0.0.1:' . parse_url($base, PHP_URL_PORT)) !== false
        && strpos($currentCmdline, $root . '/public') !== false
        && $singleWorker($pid);
    $cleanup['barrier_safe'] = $barrierSafe;
    if ($barrierSafe) {
        try {
            $db = $connect();
        } catch (Throwable $e) {
            $cleanup['connect_error_class'] = get_class($e);
            $cleanup['connect_error_sha256'] = hash('sha256', $e->getMessage());
            $barrierSafe = false;
        }
    }
    if ($barrierSafe) {
        try {
            $stmt = $db->prepare('SELECT ID,UUID,PUBLIC_TOKEN FROM '
                . $table('electronic_menu') . ' WHERE CREATE_BY=?');
            $stmt->execute([$marker]);
            $ownedMenus = $stmt->fetchAll(PDO::FETCH_ASSOC);
            if (count($ownedMenus) > ($executeCopy ? 2 : 3)) {
                throw new RuntimeException('Unexpected menu cleanup scope');
            }
            if ($executeCopy && $copyId > 0) {
                $ownedIds = array_map('intval', array_column($ownedMenus, 'id'));
                $expectedIds = [$menuId, $copyId];
                sort($ownedIds);
                sort($expectedIds);
                if ($ownedIds !== $expectedIds) {
                    throw new RuntimeException('Copied menu cleanup identity mismatch');
                }
            }
            $seenExpectedMenu = $menuId === 0;
            $relations = [];
            // Validate the entire exact-marker set before deleting any row.
            foreach ($ownedMenus as $item) {
                $ownedId = (int)$item['id'];
                if ($ownedId === $menuId) $seenExpectedMenu = true;
                if ($ownedId <= 0 || (string)$item['uuid'] === ''
                    || preg_match('/^[a-f0-9]{64}$/', (string)$item['public_token']) !== 1) {
                    throw new RuntimeException('Unrecognized synthetic menu identity');
                }
                $relations[$ownedId] = [];
                foreach (['electronic_menu_bind_code' => 'bindings',
                    'electronic_menu_device' => 'devices',
                    'electronic_menu_device_log' => 'logs'] as $name => $label) {
                    $query = $db->prepare('SELECT * FROM ' . $table($name)
                        . ' WHERE MENU_ID=? ORDER BY ID');
                    $query->execute([$ownedId]);
                    $relations[$ownedId][$label] = $query->fetchAll(PDO::FETCH_ASSOC);
                    if (!$executeDevice && !$executeExpired
                        && $relations[$ownedId][$label]) {
                        throw new RuntimeException('Menu has new relations; refusing cleanup');
                    }
                }
                if ($executeDevice || $executeExpired) {
                    $bindings = $relations[$ownedId]['bindings'];
                    $devices = $relations[$ownedId]['devices'];
                    $logs = $relations[$ownedId]['logs'];
                    if (count($bindings) > 3 || count($devices) > 2 || count($logs) > 2) {
                        throw new RuntimeException('Unexpected device relation cleanup scope');
                    }
                    $ownedDeviceIds = [];
                    foreach ($bindings as $binding) {
                        if ((int)$binding['menu_id'] !== $ownedId
                            || (string)$binding['create_by'] !== $marker
                            || preg_match('/^[a-f0-9]{64}$/',
                                (string)$binding['code_hash']) !== 1) {
                            throw new RuntimeException('Unrecognized synthetic binding row');
                        }
                    }
                    foreach ($devices as $device) {
                        if ((int)$device['menu_id'] !== $ownedId
                            || !in_array((string)$device['device_id'],
                                [$marker, $marker . 'R', $marker . 'E'], true)
                            || (string)$device['create_by'] !== 'device-bind'
                            || (int)$device['store_id'] !== 10001
                            || (string)$device['uuid'] === '') {
                            throw new RuntimeException('Unrecognized synthetic device row');
                        }
                        $ownedDeviceIds[] = (int)$device['id'];
                    }
                    foreach ($logs as $log) {
                        if ((int)$log['menu_id'] !== $ownedId
                            || !in_array((int)$log['device_record_id'],
                                $ownedDeviceIds, true)
                            || !in_array((string)$log['create_by'],
                                ['device:' . $marker, 'device:' . $marker . 'R',
                                    'device:' . $marker . 'E'], true)
                            || (string)$log['uuid'] === '') {
                            throw new RuntimeException('Unrecognized synthetic device log');
                        }
                    }
                }
            }
            $cleanup['expected_menu_seen'] = $seenExpectedMenu;
            // Delete only validated exact rows, in dependency order.
            $db->beginTransaction();
            foreach ($relations as $ownedId => $set) {
                foreach ($set['logs'] as $log) {
                    $delete = $db->prepare('DELETE FROM '
                        . $table('electronic_menu_device_log')
                        . ' WHERE ID=? AND UUID=? AND MENU_ID=?'
                        . ' AND DEVICE_RECORD_ID=? AND CREATE_BY=?');
                    $delete->execute([(int)$log['id'], (string)$log['uuid'],
                        $ownedId, (int)$log['device_record_id'],
                        (string)$log['create_by']]);
                }
                foreach ($set['devices'] as $device) {
                    $delete = $db->prepare('DELETE FROM '
                        . $table('electronic_menu_device')
                        . ' WHERE ID=? AND UUID=? AND MENU_ID=?'
                        . ' AND DEVICE_ID=? AND STORE_ID=10001');
                    $delete->execute([(int)$device['id'], (string)$device['uuid'],
                        $ownedId, (string)$device['device_id']]);
                }
                foreach ($set['bindings'] as $binding) {
                    $delete = $db->prepare('DELETE FROM '
                        . $table('electronic_menu_bind_code')
                        . ' WHERE ID=? AND MENU_ID=? AND CODE_HASH=? AND CREATE_BY=?');
                    $delete->execute([(int)$binding['id'], $ownedId,
                        (string)$binding['code_hash'], $marker]);
                }
                foreach (['electronic_menu_device_log',
                    'electronic_menu_device', 'electronic_menu_bind_code'] as $name) {
                    $query = $db->prepare('SELECT COUNT(*) FROM ' . $table($name)
                        . ' WHERE MENU_ID=?');
                    $query->execute([$ownedId]);
                    if ((int)$query->fetchColumn() !== 0) {
                        throw new RuntimeException('Device relation cleanup failed');
                    }
                }
            }
            foreach ($ownedMenus as $item) {
                $ownedId = (int)$item['id'];
                $delete = $db->prepare('DELETE FROM ' . $table('electronic_menu')
                    . ' WHERE ID=? AND UUID=? AND PUBLIC_TOKEN=? AND CREATE_BY=?');
                $delete->execute([$ownedId, (string)$item['uuid'],
                    (string)$item['public_token'], $marker]);
                $query = $db->prepare('SELECT COUNT(*) FROM ' . $table('electronic_menu')
                    . ' WHERE ID=? AND CREATE_BY=?');
                $query->execute([$ownedId, $marker]);
                if ((int)$query->fetchColumn() !== 0) {
                    throw new RuntimeException('Menu cleanup failed');
                }
            }
            $db->commit();
        } catch (Throwable $e) {
            if ($db->inTransaction()) {
                try {
                    $db->rollBack();
                } catch (Throwable $rollbackError) {
                    $cleanup['rollback_error_class'] = get_class($rollbackError);
                    $cleanup['rollback_error_sha256']
                        = hash('sha256', $rollbackError->getMessage());
                }
            }
            $cleanup['menu_error_class'] = get_class($e);
            $cleanup['menu_error_sha256'] = hash('sha256', $e->getMessage());
        }
        // Revoke the synthetic actor independently if menu cleanup needs recovery.
        try {
            $query = $db->prepare('SELECT ID FROM ' . $table('user')
                . ' WHERE UUID=? AND ACCOUNT=? AND TYPE=0 AND CREATE_BY=?');
            $query->execute([$marker, $marker, 'CODEX']);
            $ownedOperators = $query->fetchAll(PDO::FETCH_ASSOC);
            if (count($ownedOperators) > 1) throw new RuntimeException('Ambiguous operator cleanup');
            if ($ownedOperators) {
                $ownedOperatorId = (int)$ownedOperators[0]['id'];
                if ($operatorId > 0 && $ownedOperatorId !== $operatorId) {
                    throw new RuntimeException('Operator ID drift before cleanup');
                }
                $delete = $db->prepare('DELETE FROM ' . $table('user')
                    . ' WHERE ID=? AND UUID=? AND ACCOUNT=? AND TYPE=0 AND CREATE_BY=?');
                $delete->execute([$ownedOperatorId, $marker, $marker, 'CODEX']);
            }
        } catch (Throwable $e) {
            $cleanup['operator_error_class'] = get_class($e);
            $cleanup['operator_error_sha256'] = hash('sha256', $e->getMessage());
        }
    }
    try {
        $verify = $connect();
        $query = $verify->prepare('SELECT COUNT(*) FROM ' . $table('user')
            . ' WHERE UUID=? OR ACCOUNT=?');
        $query->execute([$marker, $marker]);
        $cleanup['operator_zero'] = (int)$query->fetchColumn() === 0;
        $query = $verify->prepare('SELECT COUNT(*) FROM ' . $table('electronic_menu')
            . ' WHERE CREATE_BY=?');
        $query->execute([$marker]);
        $cleanup['menu_zero'] = (int)$query->fetchColumn() === 0;
        $cleanup['menu_count_restored'] = (int)$verify->query('SELECT COUNT(*) FROM '
            . $table('electronic_menu'))->fetchColumn() === $counts['electronic_menu'];
        $cleanup['existing_menu_fingerprint_unchanged'] = $menuBefore === hash('sha256',
            serialize($verify->query($menuSourceSql)->fetchAll(PDO::FETCH_ASSOC)));
        $cleanup['relation_counts_restored'] = true;
        $cleanup['relation_fingerprints_unchanged'] = true;
        foreach (['electronic_menu_bind_code', 'electronic_menu_device',
            'electronic_menu_device_log'] as $name) {
            $currentRows = $verify->query('SELECT * FROM ' . $table($name)
                . ' ORDER BY ID')->fetchAll(PDO::FETCH_ASSOC);
            $cleanup['relation_counts_restored'] = $cleanup['relation_counts_restored']
                && count($currentRows) === $counts[$name];
            $cleanup['relation_fingerprints_unchanged']
                = $cleanup['relation_fingerprints_unchanged']
                    && hash('sha256', serialize($currentRows)) === $sourceBefore[$name];
        }
    } catch (Throwable $e) {
        $cleanup['error_class'] = get_class($e);
        $cleanup['error_sha256'] = hash('sha256', $e->getMessage());
    }
}
$clean = !empty($cleanup['operator_zero']) && !empty($cleanup['menu_zero'])
    && !empty($cleanup['menu_count_restored'])
    && !empty($cleanup['existing_menu_fingerprint_unchanged'])
    && !empty($cleanup['relation_counts_restored'])
    && !empty($cleanup['relation_fingerprints_unchanged'])
    && !empty($cleanup['barrier_safe']) && !empty($cleanup['expected_menu_seen'])
    && empty($cleanup['connect_error_class'])
    && empty($cleanup['menu_error_class']) && empty($cleanup['operator_error_class'])
    && empty($cleanup['rollback_error_class']);
echo json_encode(['lane' => $lane,
    'suite' => $executeDevice ? 'electronic-menu-device'
        : ($executeCopy ? 'electronic-menu-copy'
            : ($executeUpdate ? 'electronic-menu-update'
                : ($executeExpired ? 'electronic-menu-expired-code'
                    : 'electronic-menu-core'))),
    'marker' => $marker, 'results' => $results, 'failure' => $failure,
    'cleanup' => $cleanup], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
if ($failure !== '' || !$clean) exit(1);
