<?php

declare(strict_types=1);

// New diagnostic batch: fixed identity plus exactly two COUNT(*) queries.
$stage = 'default-deny';
set_exception_handler(static function (Throwable $e) use (&$stage): void {
    echo json_encode(['status' => 'redacted-error', 'stage' => $stage,
        'error_class' => get_class($e),
        'error_code' => (string)$e->getCode()],
        JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit(2);
});
if (($argv[1] ?? '') !== '--count-only' || count($argv) !== 2
    || (string)getenv('CDX_AI_LOG_SIZE_DIAG')
        !== 'ROOT_APPROVED_TWO_COUNTS_V1'
    || (string)getenv('CDX_AI_LOG_SIZE_DIAG_SHA')
        !== hash_file('sha256', __FILE__)) {
    echo json_encode(['status' => 'default-deny',
        'database_connected' => false, 'personal_rows_read' => false,
        'think_command_invoked' => false, 'dml_sent' => false]), PHP_EOL;
    exit(78);
}
if (PHP_VERSION_ID < 70400 || PHP_VERSION_ID >= 70500) {
    throw new RuntimeException('PHP7.4 required');
}
$stage = 'code-local-config';
$envFile = '/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local';
if (realpath($envFile) !== $envFile) {
    throw new RuntimeException('Code-local AI config unavailable');
}
$ini = parse_ini_file($envFile, true, INI_SCANNER_RAW);
$section = is_array($ini) ? ($ini['DATABASE'] ?? null) : null;
if (!is_array($section)
    || strtolower((string)($section['TYPE'] ?? 'mysql')) !== 'mysql') {
    throw new RuntimeException('Expected code-local MySQL DATABASE section');
}
foreach (['HOSTNAME', 'HOSTPORT', 'DATABASE', 'USERNAME', 'PASSWORD'] as $key) {
    if ((string)($section[$key] ?? '') === '') {
        throw new RuntimeException('Code-local AI setting absent');
    }
}
$stage = 'connection';
$dsn = 'mysql:host=' . $section['HOSTNAME']
    . ';port=' . (int)$section['HOSTPORT']
    . ';dbname=' . $section['DATABASE'] . ';charset=utf8';
try {
    $db = new PDO($dsn, $section['USERNAME'], $section['PASSWORD'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_TIMEOUT => 5,
    ]);
} catch (Throwable $e) {
    throw new RuntimeException('Code-local AI connection failed', (int)$e->getCode());
}
$stage = 'database-identity';
$identity = (string)$db->query(
    "SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())")
    ->fetchColumn();
$fingerprint = hash('sha256', $identity);
if (!hash_equals('210f925e093f71e26a8c8923f0f626e3be0a15ccff3d386bba21feef695c8a5b',
    $fingerprint)) {
    throw new RuntimeException('Not the approved developer AI MySQL database');
}
$elapsed = [];
$counts = [];
foreach (['balance_log' => 'yoshop_user_balance_log',
    'subsidy_log' => 'yoshop_user_subsidy_log'] as $label => $table) {
    $stage = 'count-' . $label;
    $start = microtime(true);
    $counts[$label] = (int)$db->query('SELECT COUNT(*) FROM ' . $table)
        ->fetchColumn();
    $elapsed[$label] = (int)round((microtime(true) - $start) * 1000);
}
echo json_encode(['status' => 'two-counts-only',
    'database_fingerprint' => $fingerprint,
    'total_rows' => $counts, 'elapsed_ms' => $elapsed,
    'personal_rows_read' => false, 'think_command_invoked' => false,
    'business_http_sent' => false, 'dml_sent' => false],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
