<?php

declare(strict_types=1);

namespace SeoScope\Install;

final class LocalConfigWriter
{
    /**
     * @param array<string, mixed> $config
     */
    public static function write(string $path, array $config): void
    {
        $export = var_export($config, true);
        $php = "<?php\n\ndeclare(strict_types=1);\n\nreturn " . $export . ";\n";
        $dir = dirname($path);
        if (!is_dir($dir) || !is_writable($dir)) {
            throw new \RuntimeException('Config directory is not writable.');
        }

        $tmp = $dir . '/.local.php.tmp.' . bin2hex(random_bytes(6));
        $written = @file_put_contents($tmp, $php, LOCK_EX);
        if ($written === false) {
            @unlink($tmp);
            throw new \RuntimeException('Cannot write configuration file.');
        }
        if (!@rename($tmp, $path)) {
            @unlink($tmp);
            throw new \RuntimeException('Cannot finalize configuration file.');
        }
    }
}
