<?php
declare(strict_types=1);

// One read-only health check of both user-approved local development MySQL schemas.
$path = realpath((string)getenv('POC_MYSQL_LOCAL_ENV'));
if ($path !== '/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local') {
    throw new RuntimeException('Explicit local AI development config required');
}
$ini = parse_ini_file($path, true, INI_SCANNER_RAW);
if (!is_array($ini)) throw new RuntimeException('Local development config unreadable');
$results = [];
foreach (['DATABASE' => 'ai_main', 'DATABASE_ZHCT' => 'store_named'] as $section => $label) {
    $config = $ini[$section] ?? [];
    foreach (['HOSTNAME', 'HOSTPORT', 'DATABASE', 'USERNAME', 'PASSWORD'] as $key) {
        if (!isset($config[$key]) || (string)$config[$key] === '') {
            throw new RuntimeException('Local development connection incomplete');
        }
    }
    $started = microtime(true);
    try {
        $pdo = new PDO('mysql:host=' . $config['HOSTNAME']
            . ';port=' . $config['HOSTPORT']
            . ';dbname=' . $config['DATABASE'] . ';charset=utf8',
            $config['USERNAME'], $config['PASSWORD'], [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_TIMEOUT => 8,
            ]);
        $value = $pdo->query('SELECT 1')->fetchColumn();
        $results[$label] = ['pass' => (int)$value === 1,
            'elapsed_ms' => (int)round((microtime(true) - $started) * 1000)];
    } catch (Throwable $error) {
        $results[$label] = ['pass' => false,
            'elapsed_ms' => (int)round((microtime(true) - $started) * 1000),
            'error_class' => get_class($error),
            'error_code' => (string)$error->getCode()];
    }
}
$pass = !in_array(false, array_column($results, 'pass'), true);
echo json_encode(['status' => $pass ? 'local-mysql-select1-pass'
    : 'local-mysql-select1-fail', 'results' => $results],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($pass ? 0 : 3);
