<?php

declare(strict_types=1);

// Read-only structural comparison. Never emits connection values or passwords.
$currentFile = (string)getenv('POC_CURRENT_CONFIG');
$templateFile = (string)getenv('POC_TEMPLATE_CONFIG');
if (!is_file($currentFile) || !is_file($templateFile)) throw new RuntimeException('Config files unavailable');
putenv('POC_DIALECT=mysql');
foreach (['HOST', 'PORT', 'SCHEMA', 'USER', 'PASSWORD', 'AI_HOST', 'AI_PORT',
    'AI_SCHEMA', 'AI_USER', 'AI_PASSWORD'] as $key) {
    putenv('POC_' . $key . '=PLACEHOLDER_' . $key);
}
$diff = static function ($old, $new, string $path = '') use (&$diff): array {
    if (!is_array($old) || !is_array($new)) return $old === $new ? [] : [$path];
    $changes = [];
    foreach (array_unique(array_merge(array_keys($old), array_keys($new))) as $key) {
        $next = $path === '' ? (string)$key : $path . '.' . $key;
        if (!array_key_exists($key, $old) || !array_key_exists($key, $new)) $changes[] = $next;
        else $changes = array_merge($changes, $diff($old[$key], $new[$key], $next));
    }
    return $changes;
};
foreach (['unset', '1'] as $flag) {
    if ($flag === 'unset') putenv('POC_MYSQL_UTF8MB4');
    else putenv('POC_MYSQL_UTF8MB4=1');
    $old = require $currentFile;
    $new = require $templateFile;
    $paths = $diff($old, $new);
    sort($paths);
    $charsets = [];
    foreach (['mysql', 'mysql_zhct'] as $connection) {
        $charsets[$connection] = [
            'current' => (string)$old['connections'][$connection]['charset'],
            'template' => (string)$new['connections'][$connection]['charset'],
        ];
    }
    echo json_encode(['flag' => $flag, 'difference_paths' => $paths,
        'charsets' => $charsets], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
}
