<?php
declare(strict_types=1);

namespace App\Core\Modules;

final class ModuleManager
{
    /** @param list<string> $paths */
    public function __construct(private readonly array $paths, private readonly string $manifestName = 'module.json')
    {
    }

    /** @return array<string,array<string,mixed>> */
    public function discover(): array
    {
        $modules = [];
        foreach ($this->paths as $path) {
            if (!is_dir($path)) {
                continue;
            }
            foreach (glob(rtrim($path, '/\\') . '/*/' . $this->manifestName) ?: [] as $manifestPath) {
                $data = json_decode((string)file_get_contents($manifestPath), true);
                if (!is_array($data) || empty($data['code'])) {
                    continue;
                }
                $data['manifest_path'] = $manifestPath;
                $data['status'] = $this->validate($data);
                $modules[(string)$data['code']] = $data;
            }
        }
        ksort($modules);
        return $modules;
    }

    /** @param array<string,mixed> $manifest */
    private function validate(array $manifest): string
    {
        foreach (['code', 'name', 'version', 'type'] as $required) {
            if (!isset($manifest[$required]) || $manifest[$required] === '') {
                return 'invalid';
            }
        }
        return 'ok';
    }
}
