<?php

declare(strict_types=1);

// Independent SELECT-only post-run audit; no HTTP and no write mode.
$lane = (string)getenv('CDX_PLATE_DELETE_LANE');
$marker = (string)getenv('CDX_PLATE_DELETE_MARKER');
if (!in_array($lane, ['A', 'B', 'C'], true)
    || ($argv[1] ?? '') !== '--audit-only'
    || !preg_match('/^CDXPLFD[A-F0-9]{16}$/D', $marker)) {
    fwrite(STDERR, "Independent marker audit disabled\n");
    exit(78);
}
$dm = $lane === 'C';
if (!$dm) {
    $cfg = require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
    if (!is_array($cfg)) throw new RuntimeException('Invalid local DB config');
    $dsn = 'mysql:host=' . $cfg['hostname'] . ';port=' . (int)($cfg['hostport'] ?? 3306)
        . ';dbname=' . $cfg['database'] . ';charset=' . ($cfg['charset'] ?? 'utf8');
} else {
    if ((string)getenv('POC_HOST') !== '127.0.0.1'
        || (string)getenv('POC_PORT') !== '5237'
        || strtoupper((string)getenv('POC_SCHEMA')) !== 'ZHCT_APP'
        || strtoupper((string)getenv('POC_USER')) !== 'ZHCT_APP') {
        throw new RuntimeException('Unexpected DM audit target');
    }
    $machineId = trim((string)@file_get_contents('/etc/machine-id'));
    if ($machineId === '' || gethostname() === false
        || hash('sha256', gethostname() . '|' . $machineId)
            !== 'd56d81988bb0f106946cce91c608fdd0ef1116e5150b23376ea87e086eace4b9') {
        throw new RuntimeException('Unexpected DM audit host');
    }
    $cfg = ['username' => getenv('POC_USER'), 'password' => getenv('POC_PASSWORD')];
    $dsn = 'dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';
}
try {
    $db = new PDO($dsn, (string)$cfg['username'], (string)$cfg['password'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_TIMEOUT => 5,
    ]);
} catch (Throwable $e) {
    throw new RuntimeException('Audit DB connect failed: ' . get_class($e));
}
$identity = $dm
    ? '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();
$approved = $dm
    ? 'bc98485aed26beab348770a82ae38dbf922b04ab88a210cd7282c4caf0156194'
    : '003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401';
if (!hash_equals($approved, hash('sha256', $identity))) {
    throw new RuntimeException('Audit DB identity mismatch');
}
$prefix = $dm ? 'YDY_' : 'ydy_';
$checks = [
    ['user', 'ACCOUNT', $marker],
    ['user', 'UUID', $marker],
    ['equipment', 'CODE', $marker],
    ['upload_file', 'CREATE_BY', $marker],
    ['upload_file', 'FILE_NAME', $marker . '.invalid'],
    ['plate_dishes', 'CREATE_BY', $marker],
];
$counts = [];
foreach ($checks as [$name, $field, $value]) {
    $table = $prefix . ($dm ? strtoupper($name) : $name);
    $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table
        . ' WHERE ' . $field . '=?');
    $stmt->execute([$value]);
    $counts[$name . '.' . strtolower($field)] = (int)$stmt->fetchColumn();
}
$root = $dm ? '/tmp/zhct-dm-poc-20260928.fcpiiN/store'
    : ($lane === 'A' ? '/tmp/zhct-http-store-a.l5omH8'
        : '/tmp/zhct-http-store-mysql.dQTTBP');
$imagePath = $root . '/public/static/upload/__codex_never_fetch__/'
    . $marker . '.invalid';
$journalDir = sys_get_temp_dir() . '/zhct-plate-file-delete-' . $marker;
$allZero = array_sum($counts) === 0;
$imageAbsent = !file_exists($imagePath);
$journalAbsent = !file_exists($journalDir);
echo json_encode(['lane' => $lane, 'marker' => $marker,
    'database_fingerprint' => hash('sha256', $identity),
    'six_exact_marker_counts' => $counts, 'all_zero' => $allZero,
    'placeholder_image_absent' => $imageAbsent,
    'private_journal_absent' => $journalAbsent],
    JSON_UNESCAPED_SLASHES) . PHP_EOL;
if (!$allZero || !$imageAbsent || !$journalAbsent) exit(1);
