#!/usr/bin/env php
<?php

$file = __DIR__ . '/../../../../config/bundles.php';

if (!file_exists($file)) {
    echo "❌ bundles.php not found.\n";
    exit(1);
}

$bundles = require $file;

if (!is_array($bundles)) {
    echo "❌ Invalid bundles.php format.\n";
    exit(1);
}

$core = [];
$serenity = [];
$others = [];

foreach ($bundles as $fqcn => $envs) {
    $fqcnWithClass = "$fqcn::class";

    if ($fqcn === 'Serenity\\CoreBundle\\SerenityCoreBundle') {
        $core[$fqcnWithClass] = $envs;
    } elseif (str_starts_with($fqcn, 'Serenity\\')) {
        $serenity[$fqcnWithClass] = $envs;
    } else {
        $others[$fqcnWithClass] = $envs;
    }
}

// Trier les autres et les Serenity (hors Core)
ksort($others);
ksort($serenity);

// Fusion finale dans l'ordre voulu
$sortedBundles = array_merge($others, $core, $serenity);

$output = "<?php\n\nreturn [\n";

foreach ($sortedBundles as $class => $envs) {
    $envExport = implode(', ', array_map(
        fn($k, $v) => var_export($k, true) . ' => ' . var_export($v, true),
        array_keys($envs),
        $envs
    ));
    $output .= "    $class => [$envExport],\n";
}

$output .= "];\n";

file_put_contents($file, $output);

echo "✅ bundles.php trié avec Serenity\\CoreBundle en premier des Serenity.\n";
