<?php

declare(strict_types=1);

// Independent read-only exact cleanup audit for one read4 permission marker.
$lane = (string)getenv('CDX_READ4_LANE');
$marker = (string)getenv('CDX_READ4_MARKER');
$roots = ['A' => '/tmp/zhct-http-store-a.l5omH8',
    'B' => '/tmp/zhct-http-store-mysql.dQTTBP',
    'C' => '/tmp/zhct-dm-poc-20260928.fcpiiN/store'];
if (($argv[1] ?? '') !== '--zero' || !isset($roots[$lane])
    || !preg_match('/^CDXBDQ4[A-F0-9]{12}$/D', $marker)
    || (string)getenv('POC_APP_ROOT') !== $roots[$lane]) {
    fwrite(STDERR, "Read4 independent zero audit disabled\n");
    exit(78);
}
$root = $roots[$lane];
if (is_link($root)) throw new RuntimeException('Read4 zero root symlink');
$config = require $root . '/application/database.php';
if (!is_array($config) || (string)($config['prefix'] ?? '') !== 'ydy_') {
    throw new RuntimeException('Read4 zero runtime config invalid');
}
$dialect = $lane === 'C' ? 'dm' : 'mysql';
if ($dialect === 'mysql') {
    $local = require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
    foreach (['hostname', 'database', 'username', 'password'] as $key) {
        if (($config[$key] ?? null) !== ($local[$key] ?? null)) {
            throw new RuntimeException('Read4 zero differs from code local');
        }
    }
    if ((string)($config['type'] ?? '') !== 'mysql'
        || (int)($config['hostport'] ?? 3306)
            !== (int)($local['hostport'] ?? 3306)) {
        throw new RuntimeException('Read4 zero MySQL target mismatch');
    }
    $dsn = 'mysql:host=' . $config['hostname'] . ';port='
        . (int)($config['hostport'] ?? 3306) . ';dbname=' . $config['database']
        . ';charset=' . (string)($config['charset'] ?? 'utf8');
    $approved = '003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401';
} else {
    if ((string)($config['type'] ?? '') !== 'app\\cores\\database\\Dm'
        || (string)getenv('POC_HOST') !== '127.0.0.1'
        || (string)getenv('POC_PORT') !== '5237'
        || strtoupper((string)getenv('POC_SCHEMA')) !== 'ZHCT_APP') {
        throw new RuntimeException('Read4 zero DM target mismatch');
    }
    foreach (['hostname' => 'POC_HOST', 'hostport' => 'POC_PORT',
        'database' => 'POC_SCHEMA', 'username' => 'POC_USER',
        'password' => 'POC_PASSWORD'] as $key => $envKey) {
        if ((string)($config[$key] ?? '') !== (string)getenv($envKey)) {
            throw new RuntimeException('Read4 zero DM worker context mismatch');
        }
    }
    $machine = trim((string)@file_get_contents('/etc/machine-id'));
    if ($machine === '' || gethostname() === false
        || hash('sha256', gethostname() . '|' . $machine)
            !== 'd56d81988bb0f106946cce91c608fdd0ef1116e5150b23376ea87e086eace4b9') {
        throw new RuntimeException('Read4 zero DM host mismatch');
    }
    $dsn = 'dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';
    $approved = 'bc98485aed26beab348770a82ae38dbf922b04ab88a210cd7282c4caf0156194';
}
$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($approved, hash('sha256', $identity))) {
    throw new RuntimeException('Read4 zero DB identity mismatch');
}
$p = $dialect === 'dm' ? 'YDY_' : 'ydy_';
$roleUuid = $marker . 'R';
$count = static function (string $sql, array $args) use ($db): int {
    $stmt = $db->prepare($sql);
    $stmt->execute($args);
    return (int)$stmt->fetchColumn();
};
$counts = [
    'user' => $count('SELECT COUNT(*) FROM ' . $p . 'user'
        . ' WHERE UUID=? OR ACCOUNT=?', [$marker, $marker]),
    'role' => $count('SELECT COUNT(*) FROM ' . $p . 'role'
        . ' WHERE UUID=? OR NAME=?', [$roleUuid, $marker]),
    'user_role' => $count('SELECT COUNT(*) FROM ' . $p . 'user_role'
        . ' WHERE USER_UUID=? OR ROLE_UUID=?', [$marker, $roleUuid]),
    'role_menu' => $count('SELECT COUNT(*) FROM ' . $p . 'role_menu'
        . ' WHERE ROLE_UUID=?', [$roleUuid]),
    'user_data' => $count('SELECT COUNT(*) FROM ' . $p . 'user_data'
        . ' WHERE USER_UUID=?', [$marker]),
];
$privateDir = sys_get_temp_dir() . '/zhct-bdq4-' . $marker;
$result = ['lane' => $lane, 'database_identity_approved' => true,
    'counts' => $counts,
    'private_journal_directory_present' => file_exists($privateDir),
    'all_zero' => array_sum($counts) === 0 && !file_exists($privateDir),
    'business_http_executed' => false, 'dml_executed' => false];
echo json_encode($result, JSON_UNESCAPED_SLASHES), PHP_EOL;
if (!$result['all_zero']) exit(1);
