<?php

declare(strict_types=1);

// READ-ONLY REVIEW BUILD. No business HTTP, payment, refund, or DML path exists.
if (($argv[1] ?? '') !== '--preflight') {
    fwrite(STDERR, "Real-payment fixture execution disabled pending review\n");
    exit(78);
}
$guard = __DIR__ . '/../parallel-order-machine-pickup-fixture/fixture_guard.php';
if (!is_file($guard)
    || hash_file('sha256', $guard)
        !== '9e625774b626db1a752b7d8a3f2a133d19516169d5fad3b9a92896e54719f32b') {
    throw new RuntimeException('Approved read-only environment guard changed');
}
require $guard;
date_default_timezone_set('PRC');
omRuntimeCheck('A');
omRuntimeCheck('B');
foreach (['/tmp/zhct-http-store-a.l5omH8',
    '/tmp/zhct-http-store-mysql.dQTTBP'] as $root) {
    foreach ([
        'application/api/service/OrderMachinePay.php'
            => '034ddbd258a085cd01e6061b7ece6c67b2e56359dc876443a900f57614d126c5',
        'application/api/service/OrderMachineConfirm.php'
            => '24c59702580895ea5c9a60c26ff27db79b3a0f8bf1dabf877bc2ab03037ba5f2',
    ] as $path => $sha) {
        if (!is_file($root . '/' . $path)
            || hash_file('sha256', $root . '/' . $path) !== $sha) {
            throw new RuntimeException('Approved formal order-machine source changed');
        }
    }
}
$harnessRoot = '/workspace/zhct/zhctprompt/work/2026-09-28-smart-canteen-dm8-poc/http-harness/';
foreach ([
    'payment_fixture_rehearsal.php'
        => '0b07609b0bbe7d7f6753b3d73e433a400e6de4fe637dab35bd6c1f2e7486c5b8',
    'payment_readback.php'
        => '3b10d1fa1969427a611a64730dd75bc840112e14dfbb58ce0859872e57f00c0f',
    'verify_admin_refund_http.php'
        => 'f2e0394ff9258ba15e3f9be06ee344e59a4c48b556ebbd4e6b17b5f1d9fa9cd6',
] as $file => $sha) {
    if (!is_file($harnessRoot . $file)
        || hash_file('sha256', $harnessRoot . $file) !== $sha) {
        throw new RuntimeException('Referenced payment/refund harness changed');
    }
}
$store = omConnectStore();
$ai = omConnectAi();
omSchemaFingerprint($store);
$today = date('Y-m-d');
$through = date('Y-m-d', strtotime('+7 day'));
$nowClock = date('H:i:s');
$mealModel = $store->query("SELECT config_value FROM ydy_config"
    . " WHERE config_key='meal_model' AND status=1 ORDER BY id DESC LIMIT 1")
    ->fetchColumn();
if ((int)$mealModel === 5) {
    throw new RuntimeException('Zhangjiagang payment branch is outside isolated stub');
}
$existingTestUsers = $store->query(
    "SELECT id,account,name,type,status,is_delete,ai_user_id FROM ydy_user"
    . " WHERE account LIKE 'CDXPAY%' AND is_delete=0 ORDER BY id DESC"
)->fetchAll();
$strictUsers = [];
$positiveWallets = 0;
$balanceSample = null;
foreach ($existingTestUsers as $user) {
    if (!preg_match('/^CDXPAY[A-F0-9]{8}$/D', (string)$user['account'])
        || (string)$user['account'] !== (string)$user['name']
        || (int)$user['type'] !== 1 || (int)$user['status'] !== 1
        || (int)$user['is_delete'] !== 0 || (int)$user['ai_user_id'] <= 0) {
        continue;
    }
    $strictUsers[] = [(int)$user['id'], (int)$user['ai_user_id']];
    $stmt = $ai->prepare('SELECT balance,subsidy_balance,gift_balance FROM yoshop_user'
        . ' WHERE user_id=?');
    $stmt->execute([(int)$user['ai_user_id']]);
    $wallet = $stmt->fetch();
    if (!is_array($wallet)) continue;
    if ((float)$wallet['balance'] + (float)$wallet['gift_balance'] >= 20.0) {
        $positiveWallets++;
    }
    if ($balanceSample === null) {
        $balanceSample = [
            'store_user_id' => (int)$user['id'],
            'ai_user_id' => (int)$user['ai_user_id'],
            'cash_balance' => (string)$wallet['balance'],
            'subsidy_balance' => (string)$wallet['subsidy_balance'],
            'gift_balance' => (string)$wallet['gift_balance'],
        ];
    }
}
$sql = 'SELECT r.ID AS restaurant_id,r.BOOK_RULES,r.PACKAGE_FEE,'
    . 'r.MORNING_END,r.NOON_END,r.NIGHT_END,r.NIGHT_SNACK_END,'
    . 'x.ID AS recipe_id,x.MENU_DATE,x.MEAL_TIMES,x.DISHES_UUID,x.LIMIT_NUM,'
    . 'd.PRICE,d.NAME FROM ydy_restaurants r'
    . ' JOIN ydy_recipes x ON x.RESTAURANT_ID=r.ID'
    . ' JOIN ydy_dishes d ON d.UUID=x.DISHES_UUID'
    . ' WHERE r.STALL_TYPE=2 AND r.STATUS=1 AND r.IS_DELETE=2'
    . ' AND x.MENU_DATE>=? AND x.MENU_DATE<=? AND d.STATUS=1 AND d.IS_DEL=1'
    . ' AND d.PRICE>0 AND d.PRICE<=20'
    . ' ORDER BY r.ID ASC,x.ID ASC';
$stmt = $store->prepare($sql);
$stmt->execute([$today, $through]);
$rowsScanned = 0;
$todayRows = 0;
$notExpired = 0;
$todayNotExpired = 0;
$notSoldOut = 0;
$deviceFree = 0;
$printerFree = 0;
$candidate = null;
foreach ($stmt as $row) {
    $rowsScanned++;
    if ($rowsScanned > 2000) throw new RuntimeException('Today menu candidate scan exceeds bound');
    $menuDate = substr((string)$row['menu_date'], 0, 10);
    if ($menuDate === $today) $todayRows++;
    $mealTimes = (int)$row['meal_times'];
    $endKey = [1 => 'morning_end', 2 => 'noon_end',
        3 => 'night_end', 4 => 'night_snack_end'][$mealTimes] ?? '';
    $end = $endKey === '' ? '' : (string)($row[$endKey] ?? '');
    if ($menuDate === $today
        && (!preg_match('/^([01]\d|2[0-3]):[0-5]\d$/D', $end)
            || $nowClock > $end . ':59')) continue;
    $notExpired++;
    if ($menuDate === $today) $todayNotExpired++;
    $rules = json_decode((string)$row['book_rules'], true);
    $methods = is_array($rules) ? ($rules['method'] ?? [1, 2]) : [1, 2];
    $methods = is_array($methods) ? $methods : [$methods];
    $methods = array_values(array_unique(array_map('intval', $methods)));
    if (!array_intersect($methods, [1, 2])) continue;
    $sold = $store->prepare('SELECT COALESCE(SUM(i.number),0) FROM ydy_initial_menu i'
        . ' JOIN ydy_meal_order m ON m.id=i.meal_order_id'
        . ' WHERE m.restaurant_id=? AND m.meal_date=? AND m.meal_times=?'
        . ' AND m.is_delete=0 AND m.order_status<>20 AND i.dishes_uuid=?');
    $sold->execute([(int)$row['restaurant_id'], $menuDate, $mealTimes,
        (string)$row['dishes_uuid']]);
    $soldNum = (int)$sold->fetchColumn();
    $limit = (int)$row['limit_num'];
    if ($limit > 0 && $soldNum >= $limit) continue;
    $notSoldOut++;
    $device = $store->prepare('SELECT COUNT(*) FROM ydy_equipment'
        . ' WHERE restaurant_id=? AND del_flag=0');
    $device->execute([(int)$row['restaurant_id']]);
    $deviceCount = (int)$device->fetchColumn();
    $printer = $store->prepare('SELECT COUNT(*) FROM ydy_equipment'
        . ' WHERE restaurant_id=? AND del_flag=0 AND type=11 AND sn<>\'\'');
    $printer->execute([(int)$row['restaurant_id']]);
    $printerCount = (int)$printer->fetchColumn();
    if ($deviceCount === 0) $deviceFree++;
    if ($printerCount === 0) $printerFree++;
    if ($candidate === null
        || ($candidate['active_printer_count'] > 0 && $printerCount === 0)
        || ($candidate['active_printer_count'] === $printerCount
            && $candidate['active_equipment_count'] > $deviceCount)
        || ($candidate['active_printer_count'] === $printerCount
            && $candidate['active_equipment_count'] === $deviceCount
            && $menuDate < $candidate['meal_date'])) {
        $candidate = [
            'restaurant_id' => (int)$row['restaurant_id'],
            'meal_date' => $menuDate,
            'meal_times' => $mealTimes,
            'dish_uuid_sha' => hash('sha256', (string)$row['dishes_uuid']),
            'dish_price' => (string)$row['price'],
            'package_fee' => (string)$row['package_fee'],
            'take_methods' => array_values(array_intersect($methods, [1, 2])),
            'active_equipment_count' => $deviceCount,
            'active_printer_count' => $printerCount,
            'remaining_if_limited' => $limit > 0 ? $limit - $soldNum : null,
            'meal_end' => $end,
        ];
    }
}
echo json_encode([
    'mode' => 'read_only_no_business_http',
    'date' => $today, 'through' => $through, 'clock' => $nowClock,
    'meal_model' => (int)$mealModel,
    'strict_existing_cdxpay_users' => count($strictUsers),
    'wallets_with_cash_or_gift_at_least_20' => $positiveWallets,
    'existing_synthetic_wallet_sample' => $balanceSample,
    'positive_price_recipe_rows_scanned' => $rowsScanned,
    'today_recipe_rows' => $todayRows,
    'today_not_expired_rows' => $todayNotExpired,
    'not_expired_or_future_rows' => $notExpired,
    'not_sold_out_rows' => $notSoldOut,
    'not_sold_out_device_free_rows' => $deviceFree,
    'not_sold_out_printer_free_rows' => $printerFree,
    'best_candidate' => $candidate,
    'business_dml' => false, 'business_http' => false,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
