<?php

declare(strict_types=1);


namespace App\Blog\Providers;

use App\Blog\Support\PluginManager;
use Illuminate\Support\Facades\File;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;

class PluginManagerServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(PluginManager::class);

        // 运行期自动加载：扫描 plugins/*/src，按 Plugins\{Vendor}\{Name} 注册 PSR-4。
        // 必须在 register() 阶段完成：Filament 面板 boot 时要解析插件页面类，
        // 第三方 ZIP 安装的插件无需修改 composer.json。
        if (is_dir(config('plugins.path'))) {
            $this->registerPluginAutoload();
        }
    }

    public function boot(): void
    {
        if (! is_dir(config('plugins.path'))) {
            return;
        }

        $manager = $this->app->make(PluginManager::class);

        foreach ($manager->all() as $key => $plugin) {
            if (! $plugin['enabled']) {
                continue;
            }

            // 依赖未满足的插件跳过加载，避免运行时缺底层能力
            if ($manager->dependencyProblems($key)) {
                continue;
            }

            $provider = $manager->resolveProvider($key);

            if ($provider && class_exists($provider)) {
                $provider::bootPlugin($manager);
            }
        }
    }

    private function registerPluginAutoload(): void
    {
        $loaders = \Composer\Autoload\ClassLoader::getRegisteredLoaders();
        $loader = reset($loaders);

        if (! $loader) {
            return;
        }

        foreach (File::directories(config('plugins.path')) as $dir) {
            $basename = basename($dir);
            [$vendor, $name] = array_pad(explode('.', $basename), 2, $basename);

            $loader->addPsr4('Plugins\\'.Str::studly($vendor).'\\'.Str::studly($name).'\\', $dir.'/src/');
        }
    }
}
