<?php
namespace Gestoreasy\Core\Module;

use Gestoreasy\Core\Routing\Router;

class ModuleManager {
    private array $loaded = [];
    public function __construct(private Router $router) {}

    public function loadModules(string $modulesDir): void {
        if (!is_dir($modulesDir)) return;
        foreach (glob($modulesDir . '/*/Module.php') as $moduleFile) {
            require_once $moduleFile;
            $ns = $this->inferNamespace($moduleFile);
            $class = $ns . '\\Module';
            if (class_exists($class)) {
                $module = new $class();
                // TODO: validar dependências quando houver grafo completo
                try {
                    $module->register($this->router);
                    $this->loaded[] = ['file' => $moduleFile, 'class' => $class, 'status' => 'registered'];
                } catch (\Throwable $e) {
                    error_log('[ModuleManager] Failed to register ' . $class . ': ' . $e->getMessage());
                    $this->loaded[] = ['file' => $moduleFile, 'class' => $class, 'status' => 'register_error'];
                    // Prosseguir com o carregamento dos demais módulos
                    continue;
                }
            } else {
                $this->loaded[] = ['file' => $moduleFile, 'class' => $class, 'status' => 'missing_class'];
            }
        }
    }

    private function inferNamespace(string $file): string {
        $dir = realpath(dirname($file)) ?: dirname($file);
        $name = basename($dir);
        return 'Modules\\' . $name;
    }

    // Debug helper
    public function debugLoaded(): array { return $this->loaded; }
}