<?php

declare(strict_types=1);

// Read-only second-process verifier. Receives no credentials or PII on argv.
$input = stream_get_contents(STDIN, 4097);
$request = is_string($input) && strlen($input) <= 4096
    ? json_decode($input, true) : null;
$orderNo = is_array($request) ? (string)($request['order_no'] ?? '') : '';
$expectedFinancialSha = is_array($request)
    ? (string)($request['financial_sha'] ?? '') : '';
if (!preg_match('/^CDXPAROM[A-F0-9]{8}A$/D', $orderNo)
    || !preg_match('/^[a-f0-9]{64}$/D', $expectedFinancialSha)) {
    fwrite(STDERR, "Independent cleanup input invalid\n");
    exit(78);
}
set_exception_handler(static function (Throwable $error): void {
    fwrite(STDERR, 'Independent cleanup audit stopped: ' . get_class($error) . "\n");
    exit(1);
});
require __DIR__ . '/fixture_guard.php';
omRuntimeCheck('A');
omRuntimeCheck('B');
$store = omConnectStore();
$ai = omConnectAi();
omSchemaFingerprint($store);
[$orders, $pickups] = omMarkerRows($store, $orderNo);
$source = omSource($store, $ai);
$actualFinancialSha = hash('sha256', serialize([
    $source['user']['balance'], $source['user']['pay_money'],
    $source['ai_user'], $source['ledgers'],
]));
$stmt = $store->prepare('SELECT COUNT(*) FROM ydy_meal_order_pickup'
    . ' WHERE restaurant_id=? AND meal_date=?');
date_default_timezone_set('PRC');
$stmt->execute([OM_RESTAURANT_ID, date('Y-m-d')]);
$candidateTodayPickup = (int)$stmt->fetchColumn();
$clean = count($orders) === 0 && count($pickups) === 0
    && $candidateTodayPickup === 0
    && hash_equals($expectedFinancialSha, $actualFinancialSha);
echo json_encode(['clean' => $clean, 'orders' => count($orders),
    'pickups' => count($pickups), 'candidate_today_pickups' => $candidateTodayPickup,
    'financial_unchanged' => hash_equals(
        $expectedFinancialSha, $actualFinancialSha),
    'marker_sha' => hash('sha256', $orderNo)],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($clean ? 0 : 1);
