<?php
declare(strict_types=1);

$lane = (string)($argv[1] ?? '');
if (!in_array($lane, ['B', 'C'], true)) {
    fwrite(STDERR, "DENIED\n"); exit(78);
}
if ($lane === 'B') {
    $config = include '/tmp/zhct-http-store-mysql.dQTTBP/application/config/local/database.php';
    if (!is_array($config) || ($config['database'] ?? '') !== 'zhct'
        || hash('sha256', (string)($config['hostname'] ?? ''))
            !== '47e8be48b0cfd56dcdb9d9d426e6637b245f340b4efad4cd2f084ec5851ecc8e') {
        throw new RuntimeException('B code-local MySQL identity drift');
    }
    $db = new PDO('mysql:host=' . $config['hostname'] . ';port=3306;dbname=zhct;charset=utf8',
        $config['username'], $config['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
    $schema = [];
    foreach (['ydy_nutrition_station', 'ydy_nutrition_station_ext', 'ydy_nutrition'] as $table) {
        $schema[$table] = array_map(static function (array $row): array {
            $row = array_change_key_case($row, CASE_LOWER);
            return [(string)$row['field'], (string)$row['null'], $row['default'] === null];
        }, $db->query('SHOW COLUMNS FROM ' . $table)->fetchAll(PDO::FETCH_ASSOC));
    }
} else {
    if (getenv('POC_DIALECT') !== 'dm' || getenv('POC_HOST') !== '127.0.0.1'
        || getenv('POC_PORT') !== '5237' || getenv('POC_SCHEMA') !== 'ZHCT_APP'
        || getenv('POC_USER') !== 'ZHCT_APP') {
        throw new RuntimeException('C isolated DM identity drift');
    }
    $db = new PDO('dm:host=127.0.0.1;port=5237;schema=ZHCT_APP',
        getenv('POC_USER'), getenv('POC_PASSWORD'),
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
    if ($db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn() !== 'ZHCT_APP') {
        throw new RuntimeException('C schema drift');
    }
    $schema = [];
    foreach (['YDY_NUTRITION_STATION', 'YDY_NUTRITION_STATION_EXT', 'YDY_NUTRITION'] as $table) {
        $query = $db->prepare('SELECT COLUMN_NAME,NULLABLE,DATA_DEFAULT FROM USER_TAB_COLUMNS WHERE TABLE_NAME=? ORDER BY COLUMN_ID');
        $query->execute([$table]);
        $schema[strtolower($table)] = array_map(static function (array $row): array {
            $row = array_change_key_case($row, CASE_LOWER);
            return [strtolower((string)$row['column_name']), (string)$row['nullable'], $row['data_default'] === null];
        }, $query->fetchAll(PDO::FETCH_ASSOC));
    }
}
$counts = [];
foreach (['ydy_nutrition_station', 'ydy_nutrition_station_ext', 'ydy_nutrition'] as $table) {
    $counts[$table] = (int)$db->query('SELECT COUNT(*) FROM ' . $table)->fetchColumn();
}
echo json_encode(['lane' => $lane, 'counts' => $counts, 'schema' => $schema,
    'business_http' => 0, 'business_dml' => 0], JSON_UNESCAPED_SLASHES), PHP_EOL;
