<?php
declare(strict_types=1);

// Read-only inventory for the two isolated HTTP workers. No credentials are printed.
$lane = (string)($argv[1] ?? '');
if (!in_array($lane, ['B', 'C'], true)) {
    throw new RuntimeException('B or C required');
}
if ($lane === 'B') {
    $cfg = parse_ini_file('/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local', true, INI_SCANNER_RAW)['DATABASE'];
    if (strtolower((string)$cfg['TYPE']) !== 'mysql' || (string)$cfg['HOSTPORT'] !== '3306') {
        throw new RuntimeException('Development MySQL config drift');
    }
    $db = new PDO('mysql:host=' . $cfg['HOSTNAME'] . ';port=' . $cfg['HOSTPORT']
        . ';dbname=' . $cfg['DATABASE'] . ';charset=utf8mb4', $cfg['USERNAME'], $cfg['PASSWORD']);
    $identity = [(string)$db->query('SELECT VERSION()')->fetchColumn(),
        (string)$db->query('SELECT DATABASE()')->fetchColumn()];
} else {
    $env = [];
    foreach (explode("\0", (string)file_get_contents('/proc/53772/environ')) as $item) {
        $part = explode('=', $item, 2);
        if (count($part) === 2) $env[$part[0]] = $part[1];
    }
    if (($env['POC_DIALECT'] ?? '') !== 'dm' || ($env['POC_AI_PORT'] ?? '') !== '5238'
        || ($env['POC_AI_SCHEMA'] ?? '') !== 'AIZHCT_APP'
        || ($env['POC_EXTERNAL_STUBS'] ?? '') !== '1') {
        throw new RuntimeException('Isolated C worker identity drift');
    }
    $db = new PDO('dm:host=127.0.0.1;port=5238;schema=AIZHCT_APP',
        $env['POC_AI_USER'], $env['POC_AI_PASSWORD']);
    $identity = ['DM8', (string)$db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn()];
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
$t = static function (string $name) use ($lane): string {
    return $lane === 'B' ? 'yoshop_' . $name : 'yoshop_' . strtoupper($name);
};
$counts = [];
foreach (['goods', 'goods_sku', 'cart', 'user'] as $name) {
    $counts[$name] = (int)$db->query('SELECT COUNT(*) FROM ' . $t($name))->fetchColumn();
}
$sql = 'SELECT g.GOODS_ID,s.GOODS_SKU_ID,s.STOCK_NUM FROM ' . $t('goods')
    . ' g JOIN ' . $t('goods_sku') . ' s ON s.GOODS_ID=g.GOODS_ID'
    . ' WHERE g.STORE_ID=10001 AND s.STORE_ID=10001 AND g.IS_DELETE=0'
    . ' AND g.STATUS=10 AND s.STOCK_NUM>=3 ORDER BY g.GOODS_ID';
$sql .= $lane === 'B' ? ' LIMIT 5' : ' FETCH FIRST 5 ROWS ONLY';
$candidates = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['lane' => $lane, 'identity' => $identity, 'counts' => $counts,
    'candidate_ids' => $candidates], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;
if (($argv[2] ?? '') === 'audit') {
    if (count($argv) !== 7) throw new RuntimeException('Four exact IDs required');
    $ids = [];
    foreach (['user', 'goods', 'sku', 'cart'] as $i => $key) {
        $value = (string)$argv[$i + 3];
        if (!preg_match('/^[1-9][0-9]*$/', $value)) throw new RuntimeException('Invalid exact ID');
        $ids[$key] = (int)$value;
    }
    $targets = [
        'user' => [$t('user'), 'USER_ID'],
        'goods' => [$t('goods'), 'GOODS_ID'],
        'sku' => [$t('goods_sku'), 'ID'],
        'cart' => [$t('cart'), 'ID'],
    ];
    $zero = [];
    foreach ($targets as $key => $target) {
        $q = $db->prepare('SELECT COUNT(*) FROM ' . $target[0]
            . ' WHERE ' . $target[1] . '=?');
        $q->execute([$ids[$key]]);
        $zero[$key] = (int)$q->fetchColumn();
    }
    echo json_encode(['independent_audit' => $zero,
        'all_zero' => array_sum($zero) === 0]) . PHP_EOL;
    if (array_sum($zero) !== 0) exit(2);
}
