<?php
declare(strict_types=1);

// Read-only, synthetic-user-only query probe; prints no configuration or row value.
$stage = 'config';
set_exception_handler(static function (Throwable $error) use (&$stage): void {
    echo json_encode(['status' => 'redacted-error', 'stage' => $stage,
        'class' => get_class($error), 'code' => (string)$error->getCode()]), PHP_EOL;
    exit(2);
});
$path = realpath((string)getenv('POC_MYSQL_LOCAL_ENV'));
if ($path !== '/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local') {
    throw new RuntimeException('Approved local development config required');
}
$config = parse_ini_file($path, true, INI_SCANNER_RAW);
if (!is_array($config) || !isset($config['DATABASE'])) {
    throw new RuntimeException('Config unavailable');
}
$db = $config['DATABASE'];
if (($db['TYPE'] ?? '') !== 'mysql' || ($db['DATABASE'] ?? '') === '') {
    throw new RuntimeException('Development MySQL required');
}
$stage = 'connect';
$pdo = new PDO('mysql:host=' . $db['HOSTNAME'] . ';port=' . $db['HOSTPORT']
    . ';dbname=' . $db['DATABASE'] . ';charset=utf8',
    $db['USERNAME'], $db['PASSWORD'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_TIMEOUT => 5,
    ]);
if ((string)$pdo->query('SELECT DATABASE()')->fetchColumn() !== $db['DATABASE']) {
    throw new RuntimeException('Wrong database');
}
$stage = 'synthetic_residue';
$stmt = $pdo->prepare('SELECT COUNT(*) FROM yoshop_user_score_log WHERE USER_ID=? AND STORE_ID=10001');
$stmt->execute([44911]);
$residue = (int)$stmt->fetchColumn();
if ($residue !== 0) throw new RuntimeException('Synthetic cleanup not zero');
$stage = 'explain';
$sql = 'SELECT ID FROM yoshop_user_score_log WHERE USER_ID=? AND STORE_ID=10001'
    . ' AND TYPE=2 AND MEAL_TIMES=1 AND DATE=? LIMIT 1';
$date = date('Y-m-d');
$explain = $pdo->prepare('EXPLAIN ' . $sql);
$explain->execute([44911, $date]);
$plan = $explain->fetchAll(PDO::FETCH_ASSOC);
$summary = [];
foreach ($plan as $row) {
    $summary[] = [
        'type' => (string)($row['type'] ?? ''),
        'key' => (string)($row['key'] ?? ''),
        'rows_estimate' => (int)($row['rows'] ?? -1),
        'extra' => (string)($row['Extra'] ?? ''),
    ];
}
$stage = 'timed_synthetic_select';
$start = microtime(true);
$probe = $pdo->prepare($sql);
$probe->execute([44911, $date]);
$found = $probe->fetchColumn();
$elapsedMs = round((microtime(true) - $start) * 1000, 3);
echo json_encode(['status' => 'read-only-probe-complete',
    'schema_identity_match' => true, 'synthetic_residue' => $residue,
    'explain' => $summary, 'synthetic_match' => $found !== false,
    'query_ms' => $elapsedMs], JSON_UNESCAPED_SLASHES), PHP_EOL;
