<?php
declare(strict_types=1);

// B-only, two fresh PDOs, SELECT-only. No business HTTP or DML.
if (count($argv) !== 2 || ($argv[1] ?? '') !== '--preflight-only'
    || (string)getenv('CDX_EM_LOG_B_HEALTH') !== 'TWO_FRESH_LOCAL_MYSQL_SELECT_V1'
    || !hash_equals((string)hash_file('sha256', __FILE__),
        (string)getenv('CDX_EM_LOG_B_HEALTH_SHA'))) {
    echo json_encode(['status' => 'default-deny', 'db_connected' => false,
        'business_http_sent' => false, 'dml_sent' => false]), PHP_EOL;
    exit(78);
}
$stage = 'runtime_identity';
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(),
        'business_http_sent' => false, 'dml_sent' => false]), PHP_EOL;
    exit(2);
});
$root = '/tmp/zhct-http-store-mysql.dQTTBP';
$pid = 10001;
if (PHP_VERSION_ID < 70300 || PHP_VERSION_ID >= 70400
    || is_link($root)
    || hash_file('sha256', $root . '/application/common/service/ElectronicMenuDevice.php')
        !== '3335769aee94126f7abfae2f2a305ba09cca9270df2ab7590657c00fabef855f'
    || hash_file('sha256', $root . '/application/api/controller/ElectronicMenu.php')
        !== '2c1df1125c5ced2abd4f97a460f4290950d8ca5fbb978d63800e76ba5d60e056') {
    throw new RuntimeException('B isolated source changed');
}
$cmd = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
$children = trim((string)@file_get_contents('/proc/' . $pid
    . '/task/' . $pid . '/children'));
if (strpos($cmd, '127.0.0.1:18081') === false
    || strpos($cmd, $root . '/public') === false || $children !== '') {
    throw new RuntimeException('B isolated listener changed');
}
$config = require $root . '/application/database.php';
$local = require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
foreach (['hostname', 'hostport', 'database', 'username', 'password', 'type'] as $key) {
    if (($config[$key] ?? null) !== ($local[$key] ?? null)) {
        throw new RuntimeException('B runtime not code-local developer MySQL');
    }
}
$dsn = 'mysql:host=' . $config['hostname'] . ';port=' . (int)$config['hostport']
    . ';dbname=' . $config['database'] . ';charset=' . ($config['charset'] ?? 'utf8');
$make = static function () use ($dsn, $config): PDO {
    return new PDO($dsn, (string)$config['username'], (string)$config['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_TIMEOUT => 5]);
};
$snapshot = static function (PDO $db): array {
    $identity = (string)$db->query(
        "SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())")
        ->fetchColumn();
    if (hash('sha256', $identity)
        !== '003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401') {
        throw new RuntimeException('Development MySQL identity changed');
    }
    if ((int)$db->query('SELECT 1')->fetchColumn() !== 1) {
        throw new RuntimeException('SELECT 1 failed');
    }
    $tables = ['electronic_menu' => 7,
        'electronic_menu_device' => 3,
        'electronic_menu_device_log' => 21];
    $counts = [];
    $digests = [];
    foreach ($tables as $short => $expected) {
        $name = 'ydy_' . $short;
        $rows = $db->query('SELECT * FROM ' . $name
            . ' ORDER BY ID')->fetchAll(PDO::FETCH_ASSOC);
        if (count($rows) !== $expected) {
            throw new RuntimeException('Original three-table row count drift');
        }
        $counts[$short] = count($rows);
        $digests[$short] = hash('sha256', serialize($rows));
    }
    $owned = [
        'menu' => (int)$db->query('SELECT COUNT(*) FROM ydy_electronic_menu'
            . " WHERE CREATE_BY LIKE 'CDXEMLOG%'")->fetchColumn(),
        'device' => (int)$db->query('SELECT COUNT(*) FROM ydy_electronic_menu_device'
            . " WHERE DEVICE_ID LIKE 'CDXEMLOG%' OR CREATE_BY LIKE 'CDXEMLOG%'")
            ->fetchColumn(),
        'log' => (int)$db->query('SELECT COUNT(*) FROM ydy_electronic_menu_device_log'
            . " WHERE CREATE_BY LIKE 'device:CDXEMLOG%'"
            . " OR EVENT_CODE LIKE 'CDXEMLOG%'")->fetchColumn(),
    ];
    if ($owned !== ['menu' => 0, 'device' => 0, 'log' => 0]) {
        throw new RuntimeException('Old owned marker not independently zero');
    }
    return ['counts' => $counts, 'digests' => $digests, 'owned' => $owned];
};
$stage = 'fresh_pdo_1';
$first = $snapshot($make());
$stage = 'fresh_pdo_2';
$second = $snapshot($make());
if ($first !== $second) {
    throw new RuntimeException('Two fresh-connection source fingerprints differ');
}
echo json_encode(['status' => 'two_fresh_select_pass',
    'environment' => 'B_code_local_dev_mysql',
    'fresh_connections' => 2, 'select_one_passes' => 2,
    'table_counts' => $first['counts'],
    'old_marker_counts' => $first['owned'],
    'three_table_fingerprints_stable_between_connections' => true,
    'historical_pre_B_hash_available' => false,
    'business_http_sent' => false, 'dml_sent' => false],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
