<?php
declare(strict_types=1);

namespace App\Foundation;

use RuntimeException;

final class ModuleRegistry
{
    /** @var array<string,array<string,mixed>> */
    private array $modules = [];

    /** @param array<string,mixed> $definition */
    public function register(string $code, array $definition): void
    {
        $module = array_merge([
            'code' => $code, 'name' => $code, 'version' => '0.0.0',
            'enabled' => true, 'legacy' => false, 'dependencies' => [],
        ], $definition);
        if (!is_array($module['dependencies'])) {
            throw new RuntimeException('Dépendances invalides pour le module ' . $code);
        }
        $this->modules[$code] = $module;
    }

    public function has(string $code): bool { return isset($this->modules[$code]); }
    /** @return array<string,mixed>|null */
    public function get(string $code): ?array { return $this->modules[$code] ?? null; }
    public function enabled(string $code): bool { return (bool)($this->modules[$code]['enabled'] ?? false); }

    /** @return list<string> */
    public function missingDependencies(string $code): array
    {
        $module = $this->get($code);
        if ($module === null) return [$code];
        $missing = [];
        foreach ($module['dependencies'] ?? [] as $dependency) {
            if (!$this->enabled((string)$dependency)) $missing[] = (string)$dependency;
        }
        return $missing;
    }

    /** @return array<string,array<string,mixed>> */
    public function all(): array { $modules = $this->modules; ksort($modules); return $modules; }
}
