<?php
declare(strict_types=1);

// Second-process read-only check after a separately approved test run.
// This script cannot create or delete a database row or cache entry.
if (getenv('CDX_READ2_ZERO_PREFLIGHT') !== '1') {
    echo json_encode(['status' => 'default_deny',
        'database_connected' => false, 'business_http_sent' => false,
        'dml_sent' => false], JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit(78);
}
$target = (string)getenv('CDX_READ2_TARGET');
$journalPath = (string)getenv('CDX_READ2_JOURNAL');
$resolved = realpath($journalPath);
$tmp = realpath(sys_get_temp_dir());
if (!in_array($target, ['A', 'B', 'C'], true)
    || !is_string($resolved) || !is_string($tmp)
    || strpos($resolved, $tmp . '/cdx-read2-') !== 0
    || basename($resolved) !== 'manifest.json') {
    throw new RuntimeException('Exact private journal and target required');
}
$dir = dirname($resolved);
if (((int)fileperms($dir) & 0777) !== 0700
    || ((int)fileperms($resolved) & 0777) !== 0600) {
    throw new RuntimeException('Private journal permissions mismatch');
}
$manifest = json_decode((string)file_get_contents($resolved), true);
if (!is_array($manifest) || ($manifest['target'] ?? null) !== $target
    || !preg_match('/^CDXPARREAD2[0-9A-F]{10}$/', (string)($manifest['marker'] ?? ''))
    || (int)($manifest['ai_user_id'] ?? 0) <= 0
    || (int)($manifest['ai_staff_id'] ?? -1) < 0
    || !preg_match('/^[a-f0-9]{64}$/', (string)($manifest['original_user_sha256'] ?? ''))
    || !preg_match('/^[a-f0-9]{64}$/', (string)($manifest['db_identity_sha256'] ?? ''))
    || ((int)$manifest['ai_staff_id'] > 0
        ? !preg_match('/^[a-f0-9]{64}$/', (string)($manifest['original_staff_sha256'] ?? ''))
        : ($manifest['original_staff_sha256'] ?? null) !== null)
    || ($manifest['phase'] ?? null) !== 'first_process_exact_zero') {
    throw new RuntimeException('First-process exact-zero journal not complete');
}

putenv('CDX_READ2_SCHEMA_PREFLIGHT=1');
require __DIR__ . '/read2_schema_preflight.php';
$runtimeRoot = [
    'A' => '/private/tmp/zhct-http-ai-macos.zjaU8h',
    'B' => '/private/tmp/zhct-http-ai-macos.x2CCZX',
    'C' => '/tmp/zhct-ai-http-20260929.3XDj3w',
][$target];
$identity = [
    'target' => $target,
    'runtime_root' => realpath($runtimeRoot),
    'http_port' => $port,
    'http_pid' => $target === 'C' ? 53772 : (int)$pids[0],
];
foreach (['POC_AI_HOST', 'POC_AI_PORT', 'POC_AI_SCHEMA', 'POC_AI_USER',
    'POC_HOST', 'POC_PORT', 'POC_SCHEMA', 'POC_USER'] as $key) {
    $identity[$key] = (string)($config[$key] ?? '');
    if ($identity[$key] === '') {
        throw new RuntimeException('Non-secret database identity incomplete');
    }
}
$identityJson = json_encode($identity, JSON_UNESCAPED_SLASHES);
if (!is_string($identityJson) || !is_string($identity['runtime_root'])
    || !hash_equals((string)$manifest['db_identity_sha256'],
        hash('sha256', $identityJson))) {
    throw new RuntimeException('Independent readback connected to a different database context');
}
$aiTableUser = $dialect === 'dm' ? 'YOSHOP_USER' : 'yoshop_user';
$aiTableStaff = $dialect === 'dm' ? 'YOSHOP_STAFF' : 'yoshop_staff';
$aiTableSubsidy = $dialect === 'dm' ? 'YOSHOP_USER_SUBSIDY' : 'yoshop_user_subsidy';
$aiTableOauth = $dialect === 'dm' ? 'YOSHOP_USER_OAUTH' : 'yoshop_user_oauth';
$aiTableBalanceLog = $dialect === 'dm' ? 'YOSHOP_USER_BALANCE_LOG' : 'yoshop_user_balance_log';
$storeTableUser = $dialect === 'dm' ? 'YDY_USER' : 'ydy_user';
$count = static function (PDO $db, string $sql, array $args): int {
    $query = $db->prepare($sql);
    $query->execute($args);
    return (int)$query->fetchColumn();
};
$userId = (int)$manifest['ai_user_id'];
$staffId = (int)$manifest['ai_staff_id'];
$marker = (string)$manifest['marker'];
$counts = [
    'ai_user_exact' => $count($ai, 'SELECT COUNT(*) FROM ' . $aiTableUser
        . ' WHERE USER_ID=? AND STORE_ID=10001 AND NICK_NAME=?', [$userId, $marker]),
    'ai_staff_exact' => $count($ai, 'SELECT COUNT(*) FROM ' . $aiTableStaff
        . ' WHERE ID=? AND USER_ID=? AND STORE_ID=10001 AND NAME=?',
        [$staffId, $userId, $marker]),
    'ai_staff_any_for_user' => $count($ai, 'SELECT COUNT(*) FROM ' . $aiTableStaff
        . ' WHERE USER_ID=? AND STORE_ID=10001', [$userId]),
    'ai_subsidy_any_for_user' => $count($ai, 'SELECT COUNT(*) FROM ' . $aiTableSubsidy
        . ' WHERE USER_ID=? AND STORE_ID=10001', [$userId]),
    'ai_oauth_any_for_user' => $count($ai, 'SELECT COUNT(*) FROM ' . $aiTableOauth
        . ' WHERE USER_ID=?', [$userId]),
    'ai_balance_log_any_for_user' => $count($ai, 'SELECT COUNT(*) FROM '
        . $aiTableBalanceLog . ' WHERE USER_ID=? AND STORE_ID=10001', [$userId]),
    'store_user_any_for_ai_user' => $count($store, 'SELECT COUNT(*) FROM '
        . $storeTableUser . ' WHERE AI_USER_ID=?', [$userId]),
];
$allZero = !in_array(true, array_map(static function (int $value): bool {
    return $value !== 0;
}, $counts), true);
echo json_encode([
    'status' => $allZero ? 'independent_second_process_exact_zero'
        : 'independent_second_process_nonzero',
    'target' => $target, 'counts' => $counts,
    'personal_rows_fetched' => 0, 'amount_values_fetched' => 0,
    'business_http_sent' => false, 'dml_sent' => false,
], JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($allZero ? 0 : 4);
