<?php
declare(strict_types=1);

// Read-only source check for the 17 public enum branches. No HTTP or DML.
$lane = (string)($argv[1] ?? '');
if (!in_array($lane, ['B', 'C'], true)) {
    fwrite(STDERR, "DENIED: exact B/C lane required\n");
    exit(78);
}

if ($lane === 'B') {
    $path = '/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local';
    $cfg = parse_ini_file($path, true, INI_SCANNER_RAW)['DATABASE'] ?? null;
    if (!is_array($cfg) || strtolower((string)($cfg['TYPE'] ?? '')) !== 'mysql'
        || (string)($cfg['HOSTPORT'] ?? '') !== '3306') {
        throw new RuntimeException('B is not code-local MySQL');
    }
    $db = new PDO('mysql:host=' . $cfg['HOSTNAME'] . ';port=' . $cfg['HOSTPORT']
        . ';dbname=' . $cfg['DATABASE'] . ';charset=utf8',
        $cfg['USERNAME'], $cfg['PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    $table = 'yoshop_config_enum';
} else {
    $pid = 53772;
    $env = [];
    foreach (explode("\0", (string)file_get_contents('/proc/' . $pid . '/environ')) as $item) {
        $parts = explode('=', $item, 2);
        if (count($parts) === 2) $env[$parts[0]] = $parts[1];
    }
    if (($env['POC_DIALECT'] ?? '') !== 'dm'
        || ($env['POC_AI_HOST'] ?? '') !== '127.0.0.1'
        || ($env['POC_AI_PORT'] ?? '') !== '5238'
        || ($env['POC_AI_SCHEMA'] ?? '') !== 'AIZHCT_APP'
        || ($env['POC_AI_USER'] ?? '') !== 'AIZHCT_APP') {
        throw new RuntimeException('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'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    if ($db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")
        ->fetchColumn() !== 'AIZHCT_APP') {
        throw new RuntimeException('C effective schema drift');
    }
    $table = 'YOSHOP_CONFIG_ENUM';
}

$rows = $db->query('SELECT ENUM_TYPE, COUNT(*) AS N FROM ' . $table
    . ' WHERE IS_DELETE=0 AND ENUM_TYPE BETWEEN 1 AND 17 GROUP BY ENUM_TYPE')
    ->fetchAll(PDO::FETCH_ASSOC);
$counts = array_fill(1, 17, 0);
foreach ($rows as $row) {
    $row = array_change_key_case($row, CASE_LOWER);
    $type = (int)$row['enum_type'];
    if ($type < 1 || $type > 17) throw new RuntimeException('Unexpected enum type');
    $counts[$type] = (int)$row['n'];
}
echo json_encode(['lane' => $lane, 'counts' => $counts,
    'total' => array_sum($counts), 'business_dml' => 0,
    'business_http' => 0], JSON_UNESCAPED_UNICODE), PHP_EOL;
