<?php
declare(strict_types=1);

namespace Celena\Core;

/**
 * Минималистичный PSR-4 автозагрузчик без composer.
 * Поддерживает несколько префиксов и базовых каталогов.
 */
final class Autoloader
{
    /** @var array<string, string[]> */
    private array $prefixes = [];

    private static ?self $instance = null;

    public static function register(string $rootPath): self
    {
        if (self::$instance !== null) return self::$instance;
        $loader = new self();
        $loader->addPrefix('Celena\\Core\\', $rootPath . '/core');
        $loader->addPrefix('Celena\\Module\\', $rootPath . '/modules');
        $loader->addPrefix('Celena\\Plugin\\', $rootPath . '/plugins');
        $loader->addPrefix('Celena\\Theme\\', $rootPath . '/templates');
        spl_autoload_register([$loader, 'load']);
        self::$instance = $loader;
        return $loader;
    }

    public static function instance(): ?self
    {
        return self::$instance;
    }

    public function addPrefix(string $prefix, string $baseDir): void
    {
        $prefix = trim($prefix, '\\') . '\\';
        $baseDir = rtrim($baseDir, '/\\');
        $this->prefixes[$prefix][] = $baseDir;
    }

    public function load(string $class): bool
    {
        foreach ($this->prefixes as $prefix => $baseDirs) {
            if (!str_starts_with($class, $prefix)) {
                continue;
            }
            $relative = substr($class, strlen($prefix));
            $relativePath = str_replace('\\', '/', $relative) . '.php';

            foreach ($baseDirs as $baseDir) {
                $file = $baseDir . '/' . $relativePath;
                if (is_file($file)) {
                    require $file;
                    return true;
                }
            }
        }
        return false;
    }
}
