<?php
declare(strict_types=1);

// Independent fresh-PDO owned-zero + four-table baseline. Never sends HTTP/DML.
$lane = (string)getenv('CDX_EM_RACE_LANE');
$journalPath = (string)getenv('CDX_EM_RACE_JOURNAL');
if (!in_array($lane, ['A', 'B', 'C'], true)
    || count($argv) !== 2 || ($argv[1] ?? '') !== '--audit'
    || (string)getenv('CDX_EM_RACE_AUDIT') !== 'ROOT_APPROVED_RACE_INDEPENDENT_ZERO_V1'
    || !hash_equals((string)hash_file('sha256', __FILE__),
        (string)getenv('CDX_EM_RACE_AUDIT_SHA'))
    || !preg_match('~^/tmp/cdx-em-race-barrier-[a-f0-9]{12}/recovery\.json$~D',
        $journalPath)) {
    echo json_encode(['status' => 'default-deny', 'db_connected' => false,
        'workers_started' => false, 'business_http_sent' => false,
        'dml_sent' => false]), PHP_EOL;
    exit(78);
}
$stage = 'private_journal';
set_exception_handler(static function (Throwable $error) use (&$stage): void {
    echo json_encode(['status' => 'redacted_stop', 'stage' => $stage,
        'error_class' => get_class($error), 'code' => (string)$error->getCode(),
        'journal_retained' => true]), PHP_EOL;
    exit(2);
});
if (is_link($journalPath) || realpath($journalPath) !== $journalPath
    || is_link(dirname($journalPath))
    || (((int)fileperms(dirname($journalPath)) & 0077) !== 0)
    || (((int)fileperms($journalPath) & 0077) !== 0)) {
    throw new RuntimeException('Private recovery journal unsafe');
}
$journal = json_decode((string)file_get_contents($journalPath), true);
if (!is_array($journal) || ($journal['lane'] ?? null) !== $lane
    || !in_array(($journal['phase'] ?? null),
        ['cleanup_committed', 'recovery_cleanup_committed'], true)
    || !preg_match('/^CDXEMRACE[A-F0-9]{12}$/D',
        (string)($journal['marker'] ?? ''))
    || !preg_match('/^[A-F0-9]{32}$/D',
        (string)($journal['menu_uuid'] ?? ''))
    || !preg_match('/^[a-f0-9]{64}$/D',
        (string)($journal['public_token'] ?? ''))
    || !preg_match('/^[a-f0-9]{64}$/D',
        (string)($journal['code_hash'] ?? ''))
    || (int)($journal['menu_id'] ?? -1) < 0
    || (int)($journal['code_id'] ?? -1) < 0
    || (($journal['phase'] ?? null) === 'cleanup_committed'
        && ((int)$journal['menu_id'] <= 0 || (int)$journal['code_id'] <= 0))
    || !is_array($journal['source_before'] ?? null)) {
    throw new RuntimeException('Owned recovery journal invalid');
}
$stage = 'fresh_approved_db_identity';
$preflight = __DIR__ . '/preflight_bind_race.php';
if (!hash_equals('915131476db82d3ab5c1a22a8fc460d8980bab07785fe53a3556988861717887',
    (string)hash_file('sha256', $preflight))) {
    throw new RuntimeException('Approved preflight changed');
}
putenv('CDX_EM_RACE_PREFLIGHT=BIND_RACE_SCHEMA_SELECT_ONLY_V1');
putenv('CDX_EM_RACE_PREFLIGHT_SHA=915131476db82d3ab5c1a22a8fc460d8980bab07785fe53a3556988861717887');
$outerArgv = $argv;
$argv[1] = '--preflight-only';
ob_start();
require $preflight;
$preflightText = (string)ob_get_clean();
$argv = $outerArgv;
restore_exception_handler();
$preflightResult = json_decode(trim($preflightText), true);
if (!is_array($preflightResult)
    || ($preflightResult['status'] ?? null) !== 'select_only_pass'
    || ($preflightResult['lane'] ?? null) !== $lane
    || ($preflightResult['old_owned_markers'] ?? null)
        !== ['menu' => 0, 'bind' => 0, 'device' => 0, 'log' => 0]) {
    throw new RuntimeException('Independent lane/marker zero preflight failed');
}
$t = static function (string $short) use ($dialect): string {
    if (!in_array($short, ['electronic_menu',
        'electronic_menu_bind_code', 'electronic_menu_device',
        'electronic_menu_device_log'], true)) {
        throw new RuntimeException('Audit table not allowlisted');
    }
    return $dialect === 'dm' ? strtoupper('ydy_' . $short) : 'ydy_' . $short;
};
$stage = 'owned_rows_and_original_fingerprints';
$q = $db->prepare('SELECT COUNT(*) FROM ' . $t('electronic_menu')
    . ' WHERE ID=? OR UUID=? OR PUBLIC_TOKEN=? OR CREATE_BY=?');
$q->execute([(int)$journal['menu_id'], $journal['menu_uuid'],
    $journal['public_token'], $journal['marker']]);
$menuCount = (int)$q->fetchColumn();
$q = $db->prepare('SELECT COUNT(*) FROM ' . $t('electronic_menu_bind_code')
    . ' WHERE ID=? OR CODE_HASH=? OR CREATE_BY=?');
$q->execute([(int)$journal['code_id'], $journal['code_hash'],
    $journal['marker']]);
$bindCount = (int)$q->fetchColumn();
$q = $db->prepare('SELECT COUNT(*) FROM ' . $t('electronic_menu_device')
    . ' WHERE MENU_ID=? OR DEVICE_ID IN (?,?)');
$q->execute([(int)$journal['menu_id'],
    $journal['device_ids'][1] ?? '', $journal['device_ids'][2] ?? '']);
$deviceCount = (int)$q->fetchColumn();
$q = $db->prepare('SELECT COUNT(*) FROM ' . $t('electronic_menu_device_log')
    . ' WHERE MENU_ID=? OR CREATE_BY LIKE ?');
$q->execute([(int)$journal['menu_id'],
    'device:' . $journal['marker'] . '%']);
$logCount = (int)$q->fetchColumn();
if ($menuCount !== 0 || $bindCount !== 0
    || $deviceCount !== 0 || $logCount !== 0) {
    throw new RuntimeException('Owned race rows remain');
}
$expected = ['electronic_menu', 'electronic_menu_bind_code',
    'electronic_menu_device', 'electronic_menu_device_log'];
$keys = array_keys($journal['source_before']);
sort($keys);
$sortedExpected = $expected;
sort($sortedExpected);
if ($keys !== $sortedExpected) {
    throw new RuntimeException('Baseline table set differs');
}
foreach ($expected as $short) {
    $actual = hash('sha256', serialize($db->query('SELECT * FROM '
        . $t($short) . ' ORDER BY ID')->fetchAll(PDO::FETCH_ASSOC)));
    if (!hash_equals((string)$journal['source_before'][$short], $actual)) {
        throw new RuntimeException('Original four-table fingerprint differs');
    }
}
$journal['phase'] = 'audited';
$journalText = json_encode($journal, JSON_UNESCAPED_SLASHES);
if (!is_string($journalText)
    || file_put_contents($journalPath, $journalText, LOCK_EX) === false
    || !chmod($journalPath, 0600)) {
    throw new RuntimeException('Private audited-phase journal write failed');
}
echo json_encode(['status' => 'independent_zero_pass', 'lane' => $lane,
    'menu_rows' => 0, 'bind_rows' => 0,
    'device_rows' => 0, 'log_rows' => 0,
    'four_table_fingerprints_restored' => true,
    'journal_phase' => 'audited',
    'journal_retained_for_worker_teardown' => true,
    'business_http_sent' => false, 'dml_sent' => false],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
