<?php
declare(strict_types=1);

// SELECT-only safety census for the current PC type=4 async export route.
// Never output connection details, config secrets, job payloads or file paths.
$lane = (string)getenv('CDX_ASYNC_LANE');
$targets = [
    'B' => ['/tmp/zhct-http-store-mysql.dQTTBP', 'mysql',
        '003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401'],
    'C' => ['/tmp/zhct-dm-poc-20260928.fcpiiN/store', 'dm',
        'bc98485aed26beab348770a82ae38dbf922b04ab88a210cd7282c4caf0156194'],
];
if (!isset($targets[$lane])) throw new RuntimeException('Unknown lane');
[$root, $dialect, $expectedIdentity] = $targets[$lane];
if (!is_dir($root) || is_link($root)) throw new RuntimeException('Unbound source root');
$config = require $root . '/application/database.php';
if (!is_array($config) || (string)($config['prefix'] ?? '') !== 'ydy_') {
    throw new RuntimeException('Unexpected config shape');
}
if ($dialect === 'mysql') {
    $local = require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
    if ((string)($config['type'] ?? '') !== 'mysql') throw new RuntimeException('Not local MySQL');
    foreach (['hostname', 'hostport', 'database', 'username', 'password'] as $key) {
        if (($config[$key] ?? null) !== ($local[$key] ?? null)) {
            throw new RuntimeException('Not code-local development MySQL');
        }
    }
    $dsn = 'mysql:host=' . $config['hostname'] . ';port=' . (int)($config['hostport'] ?? 3306)
        . ';dbname=' . $config['database'] . ';charset=' . (string)($config['charset'] ?? 'utf8');
} else {
    if ((string)($config['type'] ?? '') !== 'app\\cores\\database\\Dm'
        || (string)($config['hostname'] ?? '') !== '127.0.0.1'
        || (int)($config['hostport'] ?? 0) !== 5237
        || strtoupper((string)($config['database'] ?? '')) !== 'ZHCT_APP'
        || strtoupper((string)($config['username'] ?? '')) !== 'ZHCT_APP') {
        throw new RuntimeException('Not nonproduction DM');
    }
    $hostMark = hash('sha256', gethostname() . '|'
        . trim((string)@file_get_contents('/etc/machine-id')));
    if ($hostMark !== 'd56d81988bb0f106946cce91c608fdd0ef1116e5150b23376ea87e086eace4b9') {
        throw new RuntimeException('DM host mismatch');
    }
    $dsn = 'dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';
}
$db = 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]);
$identity = $dialect === 'mysql'
    ? (string)$db->query("SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())")->fetchColumn()
    : 'ZHCT_APP|5237|' . (string)$db->query(
        "SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn();
if (!hash_equals($expectedIdentity, hash('sha256', $identity))) {
    throw new RuntimeException('Database identity mismatch');
}
$prefix = $dialect === 'dm' ? 'YDY_' : 'ydy_';
$counts = $db->query('SELECT STATUS,COUNT(*) N FROM ' . $prefix
    . 'export_log GROUP BY STATUS')->fetchAll(PDO::FETCH_ASSOC);
$statuses = [];
foreach ($counts as $item) $statuses[(int)$item['status']] = (int)$item['n'];
$types = $db->query('SELECT TYPE,STATUS,COUNT(*) N FROM ' . $prefix
    . 'export_log WHERE TYPE=4 GROUP BY TYPE,STATUS')->fetchAll(PDO::FETCH_ASSOC);
$type4 = [];
foreach ($types as $item) $type4[(int)$item['status']] = (int)$item['n'];
$ossRows = $db->query('SELECT CONFIG_VALUE FROM ' . $prefix
    . "config WHERE CONFIG_KEY='ossDisjunctor' AND STATUS=1")->fetchAll(PDO::FETCH_COLUMN);
$ossAnyEnabled = false;
foreach ($ossRows as $value) {
    if (!empty($value)) $ossAnyEnabled = true;
}
$code = [];
foreach (['application/p/controller/MealOrder.php',
    'application/p/logic/MealOrder.php',
    'application/cron/command/ExportMealOrder.php',
    'application/common/service/XlsxStreamWriter.php'] as $relative) {
    $code[$relative] = hash_file('sha256', $root . '/' . $relative);
}
echo json_encode([
    'lane' => $lane, 'mode' => 'SELECT-only',
    'export_log_status_counts' => $statuses,
    'type4_status_counts' => $type4,
    'pending_all_types' => $statuses[0] ?? 0,
    'oss_config_rows' => count($ossRows),
    'oss_any_enabled' => $ossAnyEnabled,
    'zip_extension' => extension_loaded('zip'),
    'runtime_sha256' => $code,
], JSON_UNESCAPED_SLASHES) . PHP_EOL;
