<?php
declare(strict_types=1);

// Read-only natural-source gate for the current PC billing-record routes.
$lane = (string)($argv[1] ?? '');
if (!in_array($lane, ['B', 'C'], true)) {
    fwrite(STDERR, "lane required\n");
    exit(78);
}
$root = $lane === 'B'
    ? '/tmp/zhct-http-store-mysql.dQTTBP'
    : '/tmp/zhct-dm-poc-20260928.fcpiiN/store';
$config = require $root . '/application/database.php';
if (!is_array($config) || ($config['prefix'] ?? '') !== 'ydy_') {
    throw new RuntimeException('database config');
}
$dsn = $lane === 'C'
    ? 'dm:host=127.0.0.1;port=5237;schema=ZHCT_APP'
    : 'mysql:host=' . $config['hostname'] . ';port=' . ($config['hostport'] ?? 3306)
      . ';dbname=' . $config['database'] . ';charset=utf8mb4';
$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 = $lane === 'C'
    ? 'ZHCT_APP|5237|' . (string)$db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn()
    : (string)$db->query("SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())")->fetchColumn();
$expected = $lane === 'C'
    ? 'bc98485aed26beab348770a82ae38dbf922b04ab88a210cd7282c4caf0156194'
    : '003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401';
if (!hash_equals($expected, hash('sha256', $identity))) {
    throw new RuntimeException('database identity');
}
$p = $lane === 'C' ? 'YDY_' : 'ydy_';
$query = static function (string $sql) use ($db): array {
    if (!preg_match('/^SELECT\b/i', $sql)) throw new RuntimeException('SELECT only');
    return array_map(static function (array $row): array {
        return array_change_key_case($row, CASE_LOWER);
    }, $db->query($sql)->fetchAll(PDO::FETCH_ASSOC));
};
$bills = $query('SELECT BILL_MONTH,COUNT(*) AS N,MIN(ID) AS FIRST_ID,MAX(ID) AS LAST_ID'
    . ' FROM ' . $p . 'billing_record WHERE STORE_ID=10001 AND IS_DELETE=0'
    . ' GROUP BY BILL_MONTH ORDER BY BILL_MONTH DESC');
$details = $query('SELECT COUNT(*) AS N FROM ' . $p . 'billing_record_detail'
    . ' WHERE STORE_ID=10001 AND IS_DELETE=0');
$logs = $query('SELECT COUNT(*) AS N FROM ' . $p . 'billing_record_log'
    . ' WHERE STORE_ID=10001');
$users = $query("SELECT COUNT(*) AS N FROM " . $p . "user WHERE ACCOUNT LIKE 'CDXBILLREC%'");
$candidates = $query('SELECT B.ID,B.STATUS,B.AMOUNT,'
    . ' (SELECT COUNT(*) FROM ' . $p . 'billing_record_detail D'
    . ' WHERE D.BILL_ID=B.ID AND D.STORE_ID=10001 AND D.IS_DELETE=0) AS DETAIL_N,'
    . ' (SELECT COUNT(*) FROM ' . $p . 'billing_record_log L'
    . ' WHERE L.BILL_ID=B.ID AND L.STORE_ID=10001) AS LOG_N'
    . ' FROM ' . $p . "billing_record B WHERE B.STORE_ID=10001 AND B.IS_DELETE=0"
    . " AND B.BILL_MONTH='2026-05' ORDER BY B.ID DESC");
$candidates = array_values(array_filter($candidates, static function (array $row): bool {
    return (int)$row['detail_n'] > 0 && (int)$row['log_n'] > 0;
}));
$candidates = array_slice($candidates, 0, 3);
echo json_encode([
    'lane' => $lane,
    'identity_match' => true,
    'bill_months' => $bills,
    'details_count' => (int)($details[0]['n'] ?? 0),
    'logs_count' => (int)($logs[0]['n'] ?? 0),
    'old_actor_count' => (int)($users[0]['n'] ?? 0),
    'may_candidates' => $candidates,
], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE), PHP_EOL;
