<?php

declare(strict_types=1);

// Read-only: inspect the effective two ThinkPHP connections, never print endpoints or credentials.
$root = (string)getenv('POC_TARGET_ROOT');
$localFile = (string)getenv('POC_MYSQL_LOCAL_ENV');
$expectedCharset = (string)getenv('POC_EXPECT_CHARSET');
if (!is_file($root . '/config/database.php') || basename($localFile) !== '.env.local'
    || getenv('POC_DIALECT') !== 'mysql'
    || !in_array($expectedCharset, ['utf8', 'utf8mb4'], true)
    || ($expectedCharset === 'utf8mb4' && getenv('POC_MYSQL_UTF8MB4') !== '1')
    || ($expectedCharset === 'utf8' && getenv('POC_MYSQL_UTF8MB4') === '1')) {
    throw new RuntimeException('B4 isolated config guard failed');
}
$local = parse_ini_file($localFile, true, INI_SCANNER_RAW);
if (!is_array($local) || !isset($local['DATABASE'], $local['DATABASE_ZHCT'])) {
    throw new RuntimeException('Local development sections unavailable');
}
foreach (['DATABASE' => 'AI_', 'DATABASE_ZHCT' => ''] as $section => $prefix) {
    foreach (['HOSTNAME' => 'HOST', 'HOSTPORT' => 'PORT', 'DATABASE' => 'SCHEMA',
        'USERNAME' => 'USER', 'PASSWORD' => 'PASSWORD'] as $source => $target) {
        putenv('POC_' . $prefix . $target . '=' . (string)$local[$section][$source]);
    }
}
define('TP_ENV', 'poc');
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
require $root . '/vendor/autoload.php';
(new \think\App($root))->setEnvName('poc')->initialize();
$failed = false;
foreach (['mysql_zhct' => 'store', 'mysql' => 'ai'] as $connection => $label) {
    $config = \think\facade\Db::connect($connection)->getConfig();
    echo json_encode(['phase' => 'config', 'connection' => $label,
        'charset' => $config['charset'] ?? null], JSON_UNESCAPED_UNICODE) . PHP_EOL;
    if (($config['charset'] ?? null) !== $expectedCharset) throw new RuntimeException('Unexpected config charset');
    flush();
    try {
        for ($n = 1; $n <= 2; $n++) {
            $row = \think\facade\Db::connect($connection)
                ->query('SELECT @@character_set_client AS CLIENT_CHARSET, @@character_set_connection AS CONNECTION_CHARSET, 1 AS PROBE');
            $row = array_change_key_case((array)($row[0] ?? []), CASE_LOWER);
            echo json_encode(['phase' => 'select1', 'connection' => $label, 'attempt' => $n,
                'client_charset' => $row['client_charset'] ?? null,
                'connection_charset' => $row['connection_charset'] ?? null,
                'probe' => (int)($row['probe'] ?? -1)], JSON_UNESCAPED_UNICODE) . PHP_EOL;
            if (($row['client_charset'] ?? null) !== $expectedCharset
                || ($row['connection_charset'] ?? null) !== $expectedCharset
                || (int)($row['probe'] ?? -1) !== 1) {
                throw new RuntimeException('Unexpected effective connection charset');
            }
            flush();
        }
    } catch (Throwable $error) {
        $failed = true;
        $message = strtolower($error->getMessage());
        $category = strpos($message, 'server has gone away') !== false ? 'server-gone-away'
            : (strpos($message, 'lost connection') !== false ? 'lost-connection'
            : (strpos($message, 'timed out') !== false ? 'timeout'
            : (strpos($message, 'character set') !== false || strpos($message, 'charset') !== false
                ? 'charset-error' : 'other')));
        echo json_encode(['phase' => 'select1_failed', 'connection' => $label,
            'error_class' => get_class($error), 'error_code' => $error->getCode(),
            'error_category' => $category], JSON_UNESCAPED_UNICODE) . PHP_EOL;
        flush();
    }
}
if ($failed) exit(1);
